<?php

namespace App\Events;

use App\Models\Email;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class NewEmailReceived implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    /**
     * Create a new event instance.
     */
    public function __construct(
        public Email $email,
    ) {}

    /**
     * Get the channels the event should broadcast on.
     *
     * Broadcasts on a public channel keyed by domain.
     * Private user channels will be added when user-mailbox assignment is implemented.
     *
     * @return array<int, Channel>
     */
    public function broadcastOn(): array
    {
        return [
            new Channel('mailbox.'.$this->email->domain),
        ];
    }

    /**
     * The event's broadcast name.
     */
    public function broadcastAs(): string
    {
        return 'new.email';
    }

    /**
     * Get the data to broadcast.
     *
     * @return array<string, mixed>
     */
    public function broadcastWith(): array
    {
        return [
            'id' => $this->email->id,
            'unique_id_hash' => $this->email->unique_id_hash,
            'recipient_email' => $this->email->recipient_email,
            'sender_email' => $this->email->sender_email,
            'sender_name' => $this->email->sender_name,
            'domain' => $this->email->domain,
            'subject' => $this->email->subject,
            'preview' => $this->email->preview,
            'attachments_json' => $this->email->attachments_json,
            'attachment_size' => $this->email->attachment_size,
            'is_read' => $this->email->is_read,
            'received_at' => $this->email->received_at?->toISOString(),
        ];
    }
}
