<?php

namespace App\Listeners;

use App\EventHooks\Domain\DomainSyncExpiryDateChanged;
use App\EventHooks\Domain\DomainSyncStatusChanged;
use App\Jobs\SendEmailJob;
use App\Services\NotificationService;

/**
 * PRC-648 — Domain sync immediate (non-cron) bildirimleri. Cron batch
 * (deferred=true) flushNotifications'ta toplu gönderilir; bu listener yalnız
 * immediate'de çalışır (double yok). Admin → notifyAdmins (çoklu-kanal, yetkili admin).
 * SYNC listener (ShouldQueue DEĞİL).
 */
class SendDomainSyncNotification
{
    public function onStatusChanged(DomainSyncStatusChanged $event): void
    {
        if ($event->deferred()) {
            return;
        }
        $domain = $event->domain();
        if (! $domain) {
            return;
        }

        if ($event->notifyClient()) {
            SendEmailJob::dispatch('Domain Status Changed', 'domain', $domain->id, [
                'DOMAIN' => $domain->domain,
                'OLD_STATUS' => $event->oldStatus(),
                'NEW_STATUS' => $event->newStatus(),
                'CLIENT_NAME' => trim(($domain->client->first_name ?? '').' '.($domain->client->last_name ?? '')),
                'CHANGE_DATE' => now()->format('d.m.Y H:i'),
            ], $domain->client->language ?? 'tr', $domain->client->email ?? null);
        }

        if ($event->isCritical()) {
            app(NotificationService::class)->notifyAdmins(
                'Admin Domain Status Critical',
                "Kritik domain durumu: {$domain->domain}",
                "{$domain->domain} durumu {$event->oldStatus()} → {$event->newStatus()} olarak değişti.",
                [
                    'entity_type' => 'domain',
                    'entity_id' => $domain->id,
                    'DOMAIN' => $domain->domain,
                    'OLD_STATUS' => $event->oldStatus(),
                    'NEW_STATUS' => $event->newStatus(),
                    'CLIENT_NAME' => trim(($domain->client->first_name ?? '').' '.($domain->client->last_name ?? '')),
                    'CLIENT_ID' => $domain->client_id,
                    'REGISTRAR' => $domain->module,
                    'CHANGE_DATE' => now()->format('d.m.Y H:i'),
                ]
            );
        }
    }

    public function onExpiryChanged(DomainSyncExpiryDateChanged $event): void
    {
        if ($event->deferred()) {
            return;
        }
        $domain = $event->domain();
        if (! $domain || ! $event->notifyClient()) {
            return;
        }

        SendEmailJob::dispatch('Domain Expiry Date Changed', 'domain', $domain->id, [
            'DOMAIN' => $domain->domain,
            'OLD_EXPIRE_DATE' => $event->oldExpiry(),
            'NEW_EXPIRE_DATE' => $event->newExpiry(),
            'CLIENT_NAME' => trim(($domain->client->first_name ?? '').' '.($domain->client->last_name ?? '')),
            'CHANGE_DATE' => now()->format('d.m.Y H:i'),
        ], $domain->client->language ?? 'tr', $domain->client->email ?? null);
    }
}
