<?php

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

// FluentSMTP-style provider connections: each profile belongs to a provider
// ('smtp' = Other SMTP for now, API providers to follow) and carries its own
// sender-enforcement and connection toggles. All credentials stay in the DB.
return new class extends Migration
{
    public function up(): void
    {
        Schema::table('smtp_configs', function (Blueprint $table) {
            $table->string('provider', 40)->default('smtp')->after('user_id');
            $table->boolean('force_from_email')->default(true)->after('from_name');
            $table->boolean('force_from_name')->default(false)->after('force_from_email');
            $table->boolean('return_path_match')->default(true)->after('force_from_name');
            $table->boolean('auto_tls')->default(true)->after('encryption');
            $table->boolean('auth_enabled')->default(true)->after('auto_tls');
            $table->longText('settings')->nullable()->after('max_per_hour'); // provider-specific extras (API keys, regions, …)
        });

        // Credentials become optional when authentication is disabled
        DB::statement('ALTER TABLE smtp_configs MODIFY username VARCHAR(255) NULL');
        DB::statement('ALTER TABLE smtp_configs MODIFY password TEXT NULL');
    }

    public function down(): void
    {
        Schema::table('smtp_configs', function (Blueprint $table) {
            $table->dropColumn([
                'provider', 'force_from_email', 'force_from_name',
                'return_path_match', 'auto_tls', 'auth_enabled', 'settings',
            ]);
        });

        DB::statement('ALTER TABLE smtp_configs MODIFY username VARCHAR(255) NOT NULL');
        DB::statement('ALTER TABLE smtp_configs MODIFY password TEXT NOT NULL');
    }
};
