<?php

declare(strict_types=1);

namespace App\Http\Controllers\Customer;

use App\Domain\Account\Models\Account;
use App\Domain\Domain\Models\Domain;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;
use Inertia\Response;

/**
 * Domain Aliases / Parked Domains (cPanel "Aliases" + "Addon Domains" muadili).
 *
 * Ek bir domain'i mevcut bir hesaba bağlar (parked = aynı içerik, addon = ayrı subdir).
 * Phase 1: DB + UI; Apache vhost + DNS zone + SSL yazımı Phase 1.5'ta sysapi.
 */
class DomainAliasController extends Controller
{
    public function index(Request $request): Response
    {
        /** @var Account $account */
        $account = $request->attributes->get('customer_account');

        $aliases = DB::table('domain_aliases as a')
            ->join('domains as d', 'd.id', '=', 'a.source_domain_id')
            ->where('a.account_id', $account->id)
            ->select('a.*', 'd.name as source_domain')
            ->orderByDesc('a.id')
            ->get();

        $sourceDomains = Domain::where('account_id', $account->id)
            ->whereIn('type', ['main', 'addon'])
            ->orderBy('name')
            ->get(['id', 'name']);

        return Inertia::render('Customer/Domains/Aliases', [
            'aliases' => $aliases,
            'source_domains' => $sourceDomains,
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        /** @var Account $account */
        $account = $request->attributes->get('customer_account');

        $validated = $request->validate([
            'source_domain_id' => ['required', 'integer'],
            'alias_domain' => [
                'required', 'string', 'max:253',
                'regex:/^(?!-)[A-Za-z0-9-]{1,63}(?<!-)(\.[A-Za-z]{2,63})+$/',
            ],
            'mode' => ['required', 'in:parked,addon,wildcard_alias'],
            'auto_create_dns' => ['boolean'],
            'auto_ssl' => ['boolean'],
            'notes' => ['nullable', 'string', 'max:500'],
        ]);

        $source = Domain::where('id', $validated['source_domain_id'])
            ->where('account_id', $account->id)
            ->first();
        if (! $source) {
            return back()->with('error', 'Kaynak domain bulunamadı.');
        }

        $alias = strtolower(trim($validated['alias_domain']));

        if (Domain::where('name', $alias)->exists()) {
            return back()->with('error', "'{$alias}' başka bir hesapta ana domain olarak kayıtlı.");
        }

        if (DB::table('domain_aliases')
            ->where('alias_domain', $alias)
            ->exists()) {
            return back()->with('error', "'{$alias}' zaten alias olarak tanımlı.");
        }

        DB::table('domain_aliases')->insert([
            'account_id' => $account->id,
            'source_domain_id' => $source->id,
            'alias_domain' => $alias,
            'mode' => $validated['mode'],
            'auto_create_dns' => $validated['auto_create_dns'] ?? true,
            'auto_ssl' => $validated['auto_ssl'] ?? true,
            'status' => 'active', // Phase 1: anında aktif; Phase 1.5'ta async job
            'notes' => $validated['notes'] ?? null,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        // Phase 1.5:
        // - sysapi('vhost-alias-add', [source, alias, mode])
        // - if auto_create_dns: sysapi('zone-add', alias) + A record → source IP
        // - if auto_ssl: dispatch IssueLetsencryptJob

        return back()->with('success', "'{$alias}' → '{$source->name}' alias'ı oluşturuldu.");
    }

    public function destroy(Request $request, int $id): RedirectResponse
    {
        /** @var Account $account */
        $account = $request->attributes->get('customer_account');

        $alias = DB::table('domain_aliases')
            ->where('id', $id)
            ->where('account_id', $account->id)
            ->first();

        if (! $alias) {
            abort(404);
        }

        DB::table('domain_aliases')->where('id', $id)->delete();

        // Phase 1.5: sysapi('vhost-alias-remove', ...) + DNS zone delete + cert cleanup

        return back()->with('success', "Alias '{$alias->alias_domain}' silindi.");
    }
}
