<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Attachment;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;

class OrderConfirmationMail extends Mailable
{
    use Queueable, SerializesModels;

    /**
     * Create a new message instance.
     */
    public function __construct(public \App\Models\Order $order) {}

    public function envelope(): Envelope
    {
        return new Envelope(
            subject: "🎉 Order confirmed! #{$this->order->order_number} — God's Treat",
        );
    }

    /**
     * Get the message content definition.
     */
    public function content(): Content
    {
        return new Content(
            markdown: 'emails.order-confirmation',
        );
    }

    /**
     * Attach a freshly generated PDF invoice to the confirmation email.
     *
     * @return array<int, Attachment>
     */
    public function attachments(): array
    {
        try {
            return [
                Attachment::fromData(
                    fn () => \App\Support\InvoiceGenerator::raw($this->order),
                    \App\Support\InvoiceGenerator::filename($this->order)
                )->withMime('application/pdf'),
            ];
        } catch (\Throwable) {
            return [];
        }
    }
}
