<?php

namespace Modules\WhatsApp\Entities\Services;

use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
use Modules\WhatsApp\Entities\WaConversation;
use Modules\WhatsApp\Entities\WaMessage;

/**
 * Keeps the per-(channel, wa_id) conversation thread in sync with every message
 * that flows through the system: link the message to its thread, bump the
 * preview/last-activity, count unread inbound, and roll the Meta 24h window.
 */
class ConversationService
{
    public function resolveFor(int $businessId, ?int $channelId, string $waId, ?int $contactId = null): ?WaConversation
    {
        if ($waId === '' || !Schema::hasTable('wa_conversations')) {
            return null;
        }

        $conversation = WaConversation::firstOrCreate(
            ['business_id' => $businessId, 'channel_id' => $channelId, 'wa_id' => $waId],
            ['status' => 'open', 'ai_enabled' => true]
        );

        if ($contactId && empty($conversation->contact_id)) {
            $conversation->forceFill(['contact_id' => $contactId])->save();
        }

        return $conversation;
    }

    /**
     * Attach a (persisted) message to its conversation and update the thread
     * summary. Inbound bumps unread and (re)opens the 24h window.
     */
    public function recordMessage(WaMessage $message): ?WaConversation
    {
        if (!Schema::hasTable('wa_conversations')) {
            return null;
        }

        $conversation = $this->resolveFor(
            (int) $message->business_id,
            $message->channel_id,
            (string) $message->wa_id,
            $message->contact_id
        );
        if (!$conversation) {
            return null;
        }

        if (empty($message->conversation_id)) {
            $message->forceFill(['conversation_id' => $conversation->id])->save();
        }

        $update = [
            'last_direction'       => $message->direction,
            'last_message_excerpt' => Str::limit((string) ($message->body ?? '[' . $message->type . ']'), 180),
            'last_message_at'      => now(),
        ];

        if ($message->direction === 'in') {
            $conversation->increment('unread_count');
            $update['status'] = 'open';
            $update['window_expires_at'] = now()->addHours(24);
        }

        $conversation->forceFill($update)->save();

        return $conversation;
    }

    public function markRead(WaConversation $conversation): void
    {
        $conversation->forceFill(['unread_count' => 0])->save();
    }
}
