<?php

namespace App\Observers;

use App\Events\TicketRepliedByAdmin;
use App\Events\TicketRepliedByClient;
use App\Core\Hook\HookBridge;
use App\Models\TicketReply;

class TicketReplyObserver
{
    public function created(TicketReply $reply): void
    {
        $reply->loadMissing(['ticket', 'admin', 'client']);

        // İlk mesaj için reply event'i tetikleme (ticket açılırken eklenen ilk mesaj)
        // Ticket'ın sadece 1 reply'ı varsa, bu ilk mesajdır ve zaten TicketCreated event'i mail gönderir
        $isFirstReply = $reply->ticket->replies()->count() === 1;

        if ($reply->admin_id && $reply->admin) {
            // System log - admin ticket'a cevap verdi
            \App\Models\Log::create([
                'type' => \App\Models\Log::TYPE_SYSTEM,
                'observer' => 'TicketReplyObserver',
                'module' => 'TicketReply',
                'method' => 'created_by_admin',
                'admin_id' => $reply->admin_id,
                'client_id' => $reply->ticket->client_id,
                'ip_address' => request()->ip() ?? '0.0.0.0',
                'user_agent' => request()->userAgent(),
                'description' => "Admin {$reply->admin->name} replied to ticket #{$reply->ticket->id}",
                'request' => [
                    'entity_id' => $reply->id,
                    'ticket_id' => $reply->ticket->id,
                    'is_first_reply' => $isFirstReply,
                    'message_length' => strlen($reply->message),
                ],
            ]);

            // Sadece ilk mesaj değilse admin reply maili gönder
            if (!$isFirstReply) {
                TicketRepliedByAdmin::dispatch($reply->ticket, $reply, $reply->admin);
            }

            // WHMCS hooks
            $this->fireCreatedHooks($reply);

            return;
        }

        if ($reply->client_id && $reply->client) {
            // System log - client ticket'a cevap verdi
            \App\Models\Log::create([
                'type' => \App\Models\Log::TYPE_CLIENT,
                'observer' => 'TicketReplyObserver',
                'module' => 'TicketReply',
                'method' => 'created_by_client',
                'client_id' => $reply->client_id,
                'ip_address' => request()->ip() ?? '0.0.0.0',
                'user_agent' => request()->userAgent(),
                'description' => "Client {$reply->client->first_name} {$reply->client->last_name} replied to ticket #{$reply->ticket->id}",
                'request' => [
                    'entity_id' => $reply->id,
                    'ticket_id' => $reply->ticket->id,
                    'message_length' => strlen($reply->message),
                ],
            ]);

            // Client reply'leri için kısıtlama yok
            TicketRepliedByClient::dispatch($reply->ticket, $reply, $reply->client);

            // WHMCS hooks
            $this->fireCreatedHooks($reply);
        }
    }

    public function deleted(TicketReply $reply): void
    {
        app(HookBridge::class)->fireAction('TicketDeleteReply', [
            'ticketId'  => $reply->ticket_id,
            'ticket_id' => $reply->ticket_id,
            'replyId'   => $reply->id,
            'reply_id'  => $reply->id,
            'adminId'   => request()->user('admin')?->id,
        ]);
    }

    /**
     * Fire the appropriate WHMCS hook for a newly created reply.
     * Priority: is_internal (note) → admin author → client author.
     */
    private function fireCreatedHooks(TicketReply $reply): void
    {
        $bridge  = app(HookBridge::class);
        $ticket  = $reply->ticket;
        $baseCtx = $bridge->buildTicketReplyContext($reply, $bridge->buildTicketContext($ticket));

        // is_internal flag marks an internal note regardless of author
        if ($reply->is_internal) {
            $bridge->fireAction('TicketAddNote', array_merge($baseCtx, [
                'adminid'     => $reply->admin_id,
                'attachments' => '',
            ]));

            return;
        }

        if (! empty($reply->admin_id)) {
            $bridge->fireAction('TicketAdminReply', array_merge($baseCtx, [
                'admin' => optional($reply->admin)->name,
            ]));
        } else {
            $bridge->fireAction('TicketUserReply', $baseCtx);
        }
    }
}
