<?php

declare(strict_types=1);

namespace App\Notifications;

use App\Models\SupportTicket;
use App\Models\TicketReply;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class TicketStaffReplyNotification extends Notification implements ShouldQueue
{
    use Queueable;

    public function __construct(
        public SupportTicket $ticket,
        public TicketReply $reply,
    ) {}

    /** @return array<int, string> */
    public function via(object $notifiable): array
    {
        return ['mail', 'database'];
    }

    public function toMail(object $notifiable): MailMessage
    {
        $reference = $this->ticket->ticket_reference ?? '[EZSCALE-'.$this->ticket->id.']';
        $host = parse_url((string) config('app.url'), PHP_URL_HOST) ?: 'ezscale.cloud';
        $rawMessageId = 'ticket-'.$this->reply->id.'@'.$host;
        $storedMessageId = '<'.$rawMessageId.'>';

        // Store message_id on the reply for future threading
        $this->reply->updateQuietly(['message_id' => $storedMessageId]);

        $accountUrl = 'https://'.config('app.domains.account').'/tickets/'.$this->ticket->id;

        $mail = (new MailMessage)
            ->subject('Re: '.$this->ticket->subject.' '.$reference)
            ->replyTo((string) config('tickets.support_email'))
            ->greeting('Hello '.$notifiable->name.'!')
            ->line($this->reply->body)
            ->action('View Ticket', $accountUrl)
            ->line('Reply to this email or click the button above to respond.');

        $mail->withSymfonyMessage(function (\Symfony\Component\Mime\Email $message) use ($rawMessageId): void {
            // Remove existing Message-ID header and replace with ours
            $headers = $message->getHeaders();
            if ($headers->has('Message-ID')) {
                $headers->remove('Message-ID');
            }
            $headers->addIdHeader('Message-ID', $rawMessageId);

            $lastReply = $this->ticket->replies()
                ->whereNotNull('message_id')
                ->where('id', '!=', $this->reply->id)
                ->latest()
                ->first();

            if ($lastReply) {
                $lastId = trim((string) $lastReply->message_id, '<>');
                $headers->addIdHeader('In-Reply-To', $lastId);

                $referenceIds = $this->ticket->replies()
                    ->whereNotNull('message_id')
                    ->where('id', '!=', $this->reply->id)
                    ->pluck('message_id')
                    ->map(fn (string $id): string => trim($id, '<>'))
                    ->toArray();
                $headers->addIdHeader('References', $referenceIds);
            }
        });

        return $mail;
    }

    /** @return array<string, mixed> */
    public function toArray(object $notifiable): array
    {
        return [
            'type' => 'ticket_staff_reply',
            'ticket_id' => $this->ticket->id,
            'reply_id' => $this->reply->id,
            'subject' => $this->ticket->subject,
            'message' => 'Staff replied to your ticket: '.$this->ticket->subject,
        ];
    }
}
