<?php

declare(strict_types=1);

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        // status enum'una 'provisioning' eklenmesi (mailbox-create iş kuyruğa alındıysa).
        // MySQL ENUM tip değişikliği için MODIFY COLUMN gerekir; doctrine/dbal yok ise raw SQL.
        $driver = DB::connection()->getDriverName();
        if ($driver === 'mysql' || $driver === 'mariadb') {
            DB::statement("ALTER TABLE email_accounts MODIFY status ENUM('active','suspended','pending','provisioning') NOT NULL DEFAULT 'pending'");
        }

        Schema::table('email_accounts', function (Blueprint $table) {
            // Dovecot/Postfix vmail user UID/GID
            // Default 5000 = vmail; Phase 3'te account->linux_uid'den override edilebilir.
            $table->integer('dovecot_uid')->nullable()->default(5000)->after('password_hash');
            $table->integer('dovecot_gid')->nullable()->default(5000)->after('dovecot_uid');

            // Maildir kök dizini — örn: /var/vmail/example.com/info
            $table->string('home_dir', 255)->nullable()->after('dovecot_gid');

            // İdari enable/disable — status kolonundan bağımsız hızlı kapatma
            // (status='active' AND enabled=false → veritabanı row var ama login engelleniyor)
            $table->boolean('enabled')->default(true)->after('status');

            // IMAP/POP3 son login zamanı — analytics + idle hesap raporu için
            $table->timestamp('last_login_at')->nullable()->after('enabled');

            // Index'ler
            $table->index('enabled');
            $table->index('last_login_at');
        });
    }

    public function down(): void
    {
        Schema::table('email_accounts', function (Blueprint $table) {
            $table->dropIndex(['enabled']);
            $table->dropIndex(['last_login_at']);
            $table->dropColumn(['dovecot_uid', 'dovecot_gid', 'home_dir', 'enabled', 'last_login_at']);
        });

        $driver = DB::connection()->getDriverName();
        if ($driver === 'mysql' || $driver === 'mariadb') {
            DB::statement("ALTER TABLE email_accounts MODIFY status ENUM('active','suspended','pending') NOT NULL DEFAULT 'pending'");
        }
    }
};
