<?php

namespace App\Checklist;

use App\Contracts\GoLiveChecklist;
use App\Facades\Settings;
use Mtc\MercuryDataModels\Dealership;

class ReservationRecipientEmails extends GoLiveChecklist
{
    public function category(): string
    {
        return GoLiveChecklist::CONFIGURATION;
    }

    public function key(): string
    {
        return 'reservation_recipient_emails';
    }

    public function handle(): bool
    {
        $mtc_recipients = array_values(array_unique(array_filter(
            $this->recipientEmails(),
            fn (string $email) => $this->isMtcEmail($email),
        )));

        if (!empty($mtc_recipients)) {
            $this->failure_reason = __('go-live.errors.reservation-recipients-are-mtc', [
                'emails' => implode(', ', $mtc_recipients),
            ]);
            return false;
        }

        return true;
    }

    /**
     * Collect every configured reservation confirmation recipient: the global
     * setting plus each dealership's per-dealership override.
     *
     * @return array<int, string>
     */
    protected function recipientEmails(): array
    {
        $emails = $this->parseEmails(Settings::get('reservations-admin-team-emails'));

        Dealership::query()
            ->get()
            ->each(function (Dealership $dealership) use (&$emails) {
                $emails = array_merge($emails, $dealership->getReservationTeamEmails());
            });

        return $emails;
    }

    /**
     * Split a comma-separated recipient string into validated addresses,
     * mirroring how the reservations job parses the same value.
     *
     * @return array<int, string>
     */
    protected function parseEmails(?string $value): array
    {
        return array_values(array_filter(
            array_map('trim', explode(',', (string) $value)),
            fn (string $email) => $email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL),
        ));
    }

    protected function isMtcEmail(string $email): bool
    {
        $allowed_domains = config('auth.mtc_allowed_email_domains', ['@mtc.co.uk']);
        $email_lower = strtolower($email);

        return collect($allowed_domains)
            ->contains(fn (string $domain) => str_ends_with($email_lower, strtolower($domain)));
    }
}
