<?php

namespace App\Listeners;

use App\Events\DomainProvisioningCompleted;
use App\Models\ClientDomain;
use App\Models\ClientProduct;
use App\Models\DnsZone;
use App\Models\Setting;
use App\Services\Dns\DnsZoneService;
use Illuminate\Support\Facades\Log;

/**
 * PRC-299 Phase 2.C — co-order DNS auto-setup.
 *
 * When a domain registration completes and the same client has a
 * hosting product in the same order, automatically:
 *   1. Create a DNS zone on the configured default provider
 *   2. Add A record (@) → hosting IP
 *   3. Add A record (www) → hosting IP
 *
 * Gated by `dns_auto_setup_on_co_order` setting (default false to
 * avoid surprising existing tenants).
 */
class SetupDnsForCoOrderListener
{
    public function __construct(private DnsZoneService $zones) {}

    public function handle(DomainProvisioningCompleted $event): void
    {
        if (! Setting::getValue('dns_auto_setup_on_co_order', false)) {
            return;
        }
        if ($event->action !== 'register' || ! $event->entityId) {
            return;
        }

        $domain = ClientDomain::find($event->entityId);
        if (! $domain || ! $domain->client_id) {
            return;
        }

        // Already a zone? skip
        if (DnsZone::where('client_domain_id', $domain->id)->exists()) {
            return;
        }

        // Find a hosting product in the same order
        $hosting = $domain->order_id
            ? ClientProduct::where('client_id', $domain->client_id)
                ->where('order_id', $domain->order_id)
                ->whereNotNull('ip_address')
                ->first()
            : null;

        // Fallback: any active hosting product belonging to this client
        if (! $hosting) {
            $hosting = ClientProduct::where('client_id', $domain->client_id)
                ->whereNotNull('ip_address')
                ->where('status', 'active')
                ->latest()
                ->first();
        }

        if (! $hosting || ! $hosting->ip_address) {
            return;
        }

        try {
            $zone = $this->zones->createZone(
                $domain->domain,
                $domain->client_id,
                $domain->id,
            );
            // A records: apex + www
            $this->zones->createRecord($zone, [
                'type' => 'A',
                'name' => $domain->domain,
                'content' => $hosting->ip_address,
                'ttl' => 3600,
            ]);
            $this->zones->createRecord($zone, [
                'type' => 'A',
                'name' => 'www.'.$domain->domain,
                'content' => $hosting->ip_address,
                'ttl' => 3600,
            ]);

            Log::info('PRC-299: auto-DNS zone + A records created on co-order', [
                'domain' => $domain->domain,
                'hosting_id' => $hosting->id,
                'ip' => $hosting->ip_address,
                'zone_id' => $zone->id,
                'provider' => $zone->provider,
            ]);
        } catch (\Throwable $e) {
            Log::warning('PRC-299: auto-DNS setup failed (non-fatal): '.$e->getMessage(), [
                'domain' => $domain->domain,
                'client_id' => $domain->client_id,
            ]);
        }
    }
}
