<?php

declare(strict_types=1);

namespace App\Http\Controllers\Admin;

use App\Domain\Account\Models\Account;
use App\Domain\MailMigration\Services\MailMigrationImporter;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Inertia\Inertia;
use Inertia\Response;

/**
 * Mail Migration — cPanel pkgacct .tar.gz upload + import.
 *
 * Phase 1 MVP: tarball içinden mail accounts/forwarders parse edip
 * hedef hosting account'una (Account modeli) import eder.
 */
class MailMigrationController extends Controller
{
    public function __construct(private readonly MailMigrationImporter $importer) {}

    /**
     * Migration upload sayfası — son import'ları gösterir.
     */
    public function index(Request $request): Response
    {
        // Önceki upload'tan kalan parse sonucu (oturum'da tutuluyor)
        $previewKey = $request->session()->get('mail_migration_preview_key');
        $preview = $previewKey ? $request->session()->get('mail_migration_preview') : null;

        $accounts = Account::query()
            ->whereNull('deleted_at')
            ->orderBy('username')
            ->get(['id', 'username', 'primary_domain'])
            ->map(fn ($a) => [
                'id' => $a->id,
                'username' => $a->username,
                'primary_domain' => $a->primary_domain,
                'label' => $a->username . ($a->primary_domain ? ' (' . $a->primary_domain . ')' : ''),
            ]);

        return Inertia::render('Admin/Mail/Migration', [
            'accounts' => $accounts,
            'preview' => $preview,
            'preview_key' => $previewKey,
            'recent_imports' => $this->importer->recentImports(20),
            'is_windows_dev' => PHP_OS_FAMILY === 'Windows',
        ]);
    }

    /**
     * tar.gz dosyasını yükle ve parse et — sonucu session'a koy, redirect index.
     */
    public function uploadAndParse(Request $request): RedirectResponse
    {
        $request->validate([
            'file' => ['required', 'file', 'mimes:gz,tar,tgz', 'max:512000'], // 500 MB
            'account_id' => ['required', 'integer', 'exists:accounts,id'],
        ]);

        $file = $request->file('file');
        $filename = 'mail-migrations/' . now()->format('Ymd_His') . '_' . $file->getClientOriginalName();

        Storage::put($filename, file_get_contents($file->getRealPath()));

        $tarPath = storage_path('app/' . $filename);
        $parsed = $this->importer->parsePkgAcctTarball($tarPath);

        $previewKey = (string) \Illuminate\Support\Str::uuid();

        $request->session()->put('mail_migration_preview_key', $previewKey);
        $request->session()->put('mail_migration_preview', [
            'key' => $previewKey,
            'tar_filename' => $filename,
            'account_id' => (int) $request->input('account_id'),
            'data' => $parsed,
            'uploaded_at' => now()->toIso8601String(),
        ]);

        $msg = 'Arşiv parse edildi. ' . count($parsed['email_accounts'] ?? [])
            . ' mail hesabı, ' . count($parsed['forwarders'] ?? []) . ' forwarder bulundu.';

        if (! empty($parsed['simulated'])) {
            $msg .= ' (Simüle veriler — gerçek import değil)';
        }

        return redirect()
            ->route('admin.mail.migration.index')
            ->with('success', $msg);
    }

    /**
     * Onayla ve DB'ye import et.
     */
    public function confirmImport(Request $request): RedirectResponse
    {
        $request->validate([
            'preview_key' => ['required', 'string'],
        ]);

        $sessionKey = $request->session()->get('mail_migration_preview_key');
        $preview = $request->session()->get('mail_migration_preview');

        if (! $preview || $sessionKey !== $request->input('preview_key')) {
            return back()->with('error', 'Önizleme bulunamadı. Lütfen tekrar yükleyin.');
        }

        $account = Account::findOrFail($preview['account_id']);
        $result = $this->importer->importMailAccounts($account, $preview['data']);

        // Temizlik
        $request->session()->forget(['mail_migration_preview', 'mail_migration_preview_key']);

        // Tar dosyasını sil (audit log'tan zaten görülebilir)
        if (! empty($preview['tar_filename']) && Storage::exists($preview['tar_filename'])) {
            Storage::delete($preview['tar_filename']);
        }

        $msg = "Import tamamlandı: {$result['imported']} yeni kayıt, {$result['skipped']} atlandı";
        if (! empty($result['errors'])) {
            return redirect()
                ->route('admin.mail.migration.index')
                ->with('warning', $msg . ', ' . count($result['errors']) . ' hata oluştu.');
        }

        return redirect()
            ->route('admin.mail.migration.index')
            ->with('success', $msg . '.');
    }

    /**
     * Önizleme iptal — session'dan sil.
     */
    public function cancelPreview(Request $request): RedirectResponse
    {
        $preview = $request->session()->get('mail_migration_preview');

        if ($preview && ! empty($preview['tar_filename']) && Storage::exists($preview['tar_filename'])) {
            Storage::delete($preview['tar_filename']);
        }

        $request->session()->forget(['mail_migration_preview', 'mail_migration_preview_key']);

        return redirect()
            ->route('admin.mail.migration.index')
            ->with('success', 'Önizleme iptal edildi.');
    }
}
