<?php

namespace App\Mail;

use App\Facades\Settings;
use App\Traits\GetsColourSettings;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Collection;

class ApiCredentialsExpiringMail extends Mailable
{
    use Queueable;
    use SerializesModels;
    use GetsColourSettings;

    /**
     * Create a new message instance.
     *
     * @param Collection $oauthUsers OAuth users with expiring credentials
     * @param Collection $persistentTokens Persistent tokens expiring
     * @param int $daysUntilExpiry Days until expiry (30, 7, or 0)
     */
    public function __construct(
        private readonly Collection $oauthUsers,
        private readonly Collection $persistentTokens,
        private readonly int $daysUntilExpiry
    ) {
    }

    /**
     * Build the message.
     *
     * @return \Illuminate\Mail\Mailable
     */
    public function build()
    {
        $urgency = match ($this->daysUntilExpiry) {
            0 => 'URGENT: ',
            7 => 'Warning: ',
            default => '',
        };

        $timeframe = match ($this->daysUntilExpiry) {
            0 => 'today',
            1 => 'tomorrow',
            7 => 'in 7 days',
            30 => 'in 30 days',
            default => "in {$this->daysUntilExpiry} days",
        };

        return $this->subject("{$urgency}API Credentials Expiring {$timeframe}")
            ->view('emails.alerts.api_credentials_expiring')
            ->with([
                'oauthUsers' => $this->oauthUsers,
                'persistentTokens' => $this->persistentTokens,
                'daysUntilExpiry' => $this->daysUntilExpiry,
                'timeframe' => $timeframe,
                'site_name' => Settings::get('app-name') ?? config('app.name'),
                'site_logo' => Settings::get('site-logo') ?? ['url' => config('app.url') . '/assets/logo.svg'],
                'colours' => $this->getColourSettings(),
            ]);
    }
}
