<?php

namespace App\Services;

use App\Models\MailAccount;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Config;

class MailService
{
    /**
     * Configure the mailer with a specific mail account.
     *
     * @param MailAccount|int|null $account Mail account instance, ID, or null for default
     * @return void
     */
    public static function configureMailer($account = null): void
    {
        $mailAccount = null;

        if ($account instanceof MailAccount) {
            $mailAccount = $account;
        } elseif (is_numeric($account)) {
            $mailAccount = MailAccount::find($account);
        } else {
            // Use default account
            $mailAccount = MailAccount::default()->active()->first();
        }

        if (!$mailAccount) {
            // Fall back to config-based mailer
            return;
        }

        // Configure SMTP mailer dynamically
        $config = $mailAccount->getSmtpConfigArray();

        Config::set('mail.mailers.smtp', $config);
        Config::set('mail.from', $config['from']);
        Config::set('mail.default', 'smtp');

        // Purge the mailer instance to force reconfiguration
        Mail::forgetMailers();
    }

    /**
     * Send an email using a specific mail account.
     *
     * @param mixed $mailable The mailable instance
     * @param MailAccount|int|null $account Mail account to use
     * @return void
     */
    public static function sendWith($mailable, $account = null): void
    {
        static::configureMailer($account);
        Mail::send($mailable);
    }

    /**
     * Get the default mail account.
     *
     * @return MailAccount|null
     */
    public static function getDefaultAccount(): ?MailAccount
    {
        return MailAccount::default()->active()->first();
    }

    /**
     * Get mail account for a specific department.
     *
     * @param int $departmentId
     * @return MailAccount|null
     */
    public static function getAccountForDepartment(int $departmentId): ?MailAccount
    {
        $department = \App\Models\Departments::find($departmentId);

        if (!$department || !$department->mail_account_id) {
            return static::getDefaultAccount();
        }

        return MailAccount::find($department->mail_account_id);
    }
}
