<?php

use App\Support\Providers\ProviderCredentialKind;
use App\Support\Providers\ProviderCredentialSource;
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
    {
        if (! Schema::hasTable('provider_credentials')) {
            return;
        }

        Schema::table('provider_credentials', function (Blueprint $table): void {
            $table->string('credential_kind')->nullable()->after('type');
            $table->string('source')->nullable()->after('credential_kind');
            $table->timestamp('last_rotated_at')->nullable()->after('source');
            $table->timestamp('expires_at')->nullable()->after('last_rotated_at');
        });

        DB::statement(sprintf(
            <<<'SQL'
                UPDATE provider_credentials
                SET credential_kind = COALESCE(NULLIF(type, ''), '%s'),
                    source = COALESCE(source, '%s'),
                    last_rotated_at = COALESCE(last_rotated_at, updated_at, created_at)
            SQL,
            ProviderCredentialKind::ClientSecret->value,
            ProviderCredentialSource::LegacyMigrated->value,
        ));
    }

    public function down(): void
    {
        if (! Schema::hasTable('provider_credentials')) {
            return;
        }

        Schema::table('provider_credentials', function (Blueprint $table): void {
            $table->dropColumn([
                'credential_kind',
                'source',
                'last_rotated_at',
                'expires_at',
            ]);
        });
    }
};
