<?php

declare(strict_types=1);

namespace App\Notifications;

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

class InvoiceGeneratedNotification extends Notification implements ShouldQueue
{
    use Queueable;

    public function __construct(
        public Invoice $invoice,
    ) {}

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

    public function toMail(object $notifiable): MailMessage
    {
        $amount = number_format((float) $this->invoice->total, 2);
        $currency = strtoupper($this->invoice->currency);
        $invoiceUrl = 'https://'.config('app.domains.account').'/billing/invoices';

        $mail = (new MailMessage)
            ->subject("Invoice #{$this->invoice->number} - {$currency} {$amount}")
            ->greeting("Hello {$notifiable->name},")
            ->line('A new invoice has been generated for your account.')
            ->line("Invoice: **#{$this->invoice->number}**")
            ->line("Amount: **{$currency} {$amount}**");

        if ($this->invoice->due_date) {
            $dueDate = $this->invoice->due_date->format('M j, Y');
            $mail->line("Due date: **{$dueDate}**");
        }

        return $mail
            ->action('View Invoices', $invoiceUrl)
            ->line('Thank you for your business!');
    }

    /** @return array<string, mixed> */
    public function toArray(object $notifiable): array
    {
        return [
            'type' => 'invoice_generated',
            'invoice_id' => $this->invoice->id,
            'invoice_number' => $this->invoice->number,
            'total' => $this->invoice->total,
            'currency' => $this->invoice->currency,
            'due_date' => $this->invoice->due_date?->toDateString(),
            'message' => "Invoice #{$this->invoice->number} generated for {$this->invoice->currency} {$this->invoice->total}.",
        ];
    }
}
