<?php

declare(strict_types=1);

namespace Maestro\Core\Modules\Invoices\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Attachment;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
use Maestro\Core\Models\Organization;

final class InvoiceSentMailable extends Mailable
{
    use Queueable, SerializesModels;

    /**
     * @param  array<string, mixed>  $document  InvoiceDocumentBuilder payload
     */
    public function __construct(
        public Organization $organization,
        public array $document,
        public string $pdfBinary,
        public string $pdfFilename,
        public string $bodyHtml = '',
    ) {}

    public function envelope(): Envelope
    {
        $num = (string) ($this->document['document_number'] ?? '');
        $subject = sprintf(
            '%s — %s %s',
            $this->organization->display_name,
            $this->document['type_label'] ?? 'Invoice',
            $num
        );

        return new Envelope(subject: $subject);
    }

    public function content(): Content
    {
        return new Content(
            html: 'maestro-core::invoices.mail.sent',
            with: [
                'organizationName' => $this->organization->display_name,
                'documentNumber' => (string) ($this->document['document_number'] ?? ''),
                'docLabel' => strtolower((string) ($this->document['type_label'] ?? 'invoice')),
                'bodyHtml' => $this->bodyHtml,
            ],
        );
    }

    /**
     * @return array<int, Attachment>
     */
    public function attachments(): array
    {
        return [
            Attachment::fromData(fn (): string => $this->pdfBinary, $this->pdfFilename)
                ->withMime('application/pdf'),
        ];
    }
}
