<?php

namespace App\Mail;

use App\Models\EmailMessage;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Address;
use Illuminate\Mail\Mailables\Attachment;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;

class OutgoingSchoolEmail extends Mailable
{
    use Queueable, SerializesModels;

    public function __construct(
        public EmailMessage $emailMessage,
    ) {}

    public function envelope(): Envelope
    {
        $envelope = new Envelope(
            subject: $this->emailMessage->subject,
            from: new Address($this->emailMessage->from_address, $this->emailMessage->from_name ?? ''),
        );

        if ($this->emailMessage->reply_to) {
            $envelope->replyTo = [new Address($this->emailMessage->reply_to)];
        }

        if ($this->emailMessage->cc) {
            $envelope->cc = array_map(fn (string $email) => new Address($email), $this->emailMessage->cc);
        }

        if ($this->emailMessage->bcc) {
            $envelope->bcc = array_map(fn (string $email) => new Address($email), $this->emailMessage->bcc);
        }

        return $envelope;
    }

    public function content(): Content
    {
        return new Content(
            htmlString: $this->emailMessage->body_html,
        );
    }

    /**
     * @return array<int, Attachment>
     */
    public function attachments(): array
    {
        return $this->emailMessage->attachments
            ->map(fn ($attachment) => Attachment::fromData(
                fn () => $attachment->contents(),
                $attachment->filename,
            )->withMime($attachment->mime_type))
            ->all();
    }
}
