<?php

namespace App\Modules\Addon\MigrateWhmcs;

use App\Core\Addon\AbstractAddon;
use App\Modules\Addon\MigrateWhmcs\Services\ImportOrchestrator;
use App\Modules\Addon\MigrateWhmcs\Services\MigrationLedger;
use App\Modules\Addon\MigrateWhmcs\Services\WhmcsSourceConnection;
use Illuminate\Support\Facades\DB;

/**
 * PRC-1113 — Migrate-from-WHMCS addon. Admin-only; WHMCS DB'den procp'ye tek-yönlü
 * göç. Kaynak SALT-OKUNUR. Idempotent (ledger) + dry-run. Faz-1 fault-isolation ile
 * sarılı (AddonDispatchController try/catch).
 */
class MigrateWhmcs extends AbstractAddon
{
    /**
     * WHMCS DB bağlantı creds'i (encrypted settings). Şifre asla log'lanmaz.
     */
    public function configFields(): array
    {
        return [
            'whmcs_db_host' => ['type' => 'text', 'label' => 'WHMCS DB Host', 'default' => '127.0.0.1'],
            'whmcs_db_port' => ['type' => 'text', 'label' => 'WHMCS DB Port', 'default' => '3306'],
            'whmcs_db_name' => ['type' => 'text', 'label' => 'WHMCS DB Name'],
            'whmcs_db_user' => ['type' => 'text', 'label' => 'WHMCS DB User'],
            'whmcs_db_pass' => ['type' => 'password', 'label' => 'WHMCS DB Password', 'encrypted' => true],
        ];
    }

    /**
     * Ayarlardan WHMCS bağlantı creds'ini derle.
     */
    protected function creds(): array
    {
        return [
            'host' => $this->getSetting('whmcs_db_host', '127.0.0.1'),
            'port' => $this->getSetting('whmcs_db_port', '3306'),
            'database' => $this->getSetting('whmcs_db_name', ''),
            'username' => $this->getSetting('whmcs_db_user', ''),
            'password' => $this->getSetting('whmcs_db_pass', ''),
        ];
    }

    /**
     * Admin surface — action router + UI render. Faz-1 dispatcher bu çağrıyı
     * try/catch'e sarar; buradaki bir exception admin chrome'unu düşürmez.
     */
    public function adminOutput(array $ctx): mixed
    {
        $action = $ctx['action'] ?? null;
        $request = $ctx['request'] ?? request();

        return match ($action) {
            'test-connection' => $this->handleTestConnection(),
            'dry-run' => $this->handleRun(true),
            'import' => $this->handleRun(false),
            default => $this->renderDashboard(),
        };
    }

    /**
     * Clientarea yüzeyi yok (admin-only göç aracı).
     */
    public function clientareaOutput(array $ctx): mixed
    {
        abort(404);
    }

    protected function handleTestConnection(): mixed
    {
        $result = WhmcsSourceConnection::test($this->creds());

        return redirect()
            ->route('admin.addons.dispatch', ['name' => $this->name()])
            ->with($result['ok'] ? 'success' : 'error', $result['message']
                .($result['ok'] ? " ({$result['client_count']} client)" : ''));
    }

    protected function handleRun(bool $dryRun): mixed
    {
        $orchestrator = new ImportOrchestrator(new MigrationLedger());
        $report = $orchestrator->run($this->creds(), $dryRun);

        session()->flash('whmcs_report', $report->toArray());
        session()->flash('whmcs_report_dry', $dryRun);

        return redirect()
            ->route('admin.addons.dispatch', ['name' => $this->name()])
            ->with('success', $dryRun ? 'Dry-run tamamlandı — aşağıdaki rapora bakın.' : 'Göç tamamlandı.');
    }

    protected function renderDashboard(): mixed
    {
        $ledger = new MigrationLedger();

        return view('addon-migrate-whmcs::admin', [
            'addonName' => $this->name(),
            'creds' => $this->creds(),
            'counts' => [
                'client' => $ledger->countByType('client'),
                'domain' => $ledger->countByType('domain'),
                'service' => $ledger->countByType('service'),
                'invoice' => $ledger->countByType('invoice'),
                'order' => $ledger->countByType('order'),
                'ticket' => $ledger->countByType('ticket'),
            ],
            'productMap' => DB::table('whmcs_product_map')->count(),
            'tldMap' => DB::table('whmcs_tld_map')->count(),
            'currencyMap' => DB::table('whmcs_currency_map')->count(),
            'report' => session('whmcs_report'),
            'reportDry' => session('whmcs_report_dry'),
        ]);
    }
}
