<?php

use App\Support\Providers\ProviderConnectionType;
use App\Support\Providers\ProviderConsentStatus;
use App\Support\Providers\ProviderVerificationStatus;
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_connections')) {
            return;
        }

        Schema::table('provider_connections', function (Blueprint $table): void {
            $table->string('connection_type')
                ->default(ProviderConnectionType::Platform->value)
                ->after('is_default');
            $table->string('consent_status')
                ->default(ProviderConsentStatus::Required->value)
                ->after('status');
            $table->timestamp('consent_granted_at')->nullable()->after('consent_status');
            $table->timestamp('consent_last_checked_at')->nullable()->after('consent_granted_at');
            $table->string('consent_error_code')->nullable()->after('consent_last_checked_at');
            $table->string('consent_error_message')->nullable()->after('consent_error_code');
            $table->string('verification_status')
                ->default(ProviderVerificationStatus::Unknown->value)
                ->after('consent_error_message');
            $table->boolean('migration_review_required')->default(false)->after('health_status');
            $table->timestamp('migration_reviewed_at')->nullable()->after('migration_review_required');

            $table->index(
                ['workspace_id', 'provider', 'connection_type'],
                'provider_connections_workspace_provider_connection_type_idx',
            );
            $table->index(
                ['workspace_id', 'provider', 'consent_status'],
                'provider_connections_workspace_provider_consent_status_idx',
            );
            $table->index(
                ['workspace_id', 'provider', 'verification_status'],
                'provider_connections_workspace_provider_verification_status_idx',
            );
            $table->index(
                ['workspace_id', 'provider', 'migration_review_required'],
                'provider_connections_workspace_provider_review_required_idx',
            );
        });

        DB::statement(sprintf(
            <<<'SQL'
                UPDATE provider_connections
                SET connection_type = '%s',
                    consent_status = CASE
                        WHEN status = 'connected' THEN '%s'
                        WHEN COALESCE(last_error_reason_code, '') = 'provider_consent_revoked' THEN '%s'
                        WHEN status = 'error' AND COALESCE(last_error_reason_code, '') <> 'provider_consent_missing' THEN '%s'
                        ELSE '%s'
                    END,
                    consent_granted_at = CASE
                        WHEN status = 'connected' THEN COALESCE(last_health_check_at, updated_at, created_at)
                        ELSE NULL
                    END,
                    consent_last_checked_at = CASE
                        WHEN status = 'connected' THEN COALESCE(last_health_check_at, updated_at, created_at)
                        ELSE NULL
                    END,
                    consent_error_code = CASE
                        WHEN status = 'error' THEN last_error_reason_code
                        ELSE NULL
                    END,
                    consent_error_message = CASE
                        WHEN status = 'error' THEN last_error_message
                        ELSE NULL
                    END,
                    verification_status = CASE
                        WHEN health_status = 'ok' THEN '%s'
                        WHEN health_status = 'degraded' THEN '%s'
                        WHEN health_status = 'down' THEN '%s'
                        ELSE '%s'
                    END
            SQL,
            ProviderConnectionType::Platform->value,
            ProviderConsentStatus::Granted->value,
            ProviderConsentStatus::Revoked->value,
            ProviderConsentStatus::Failed->value,
            ProviderConsentStatus::Required->value,
            ProviderVerificationStatus::Healthy->value,
            ProviderVerificationStatus::Degraded->value,
            ProviderVerificationStatus::Error->value,
            ProviderVerificationStatus::Unknown->value,
        ));
    }

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

        Schema::table('provider_connections', function (Blueprint $table): void {
            $table->dropIndex('provider_connections_workspace_provider_connection_type_idx');
            $table->dropIndex('provider_connections_workspace_provider_consent_status_idx');
            $table->dropIndex('provider_connections_workspace_provider_verification_status_idx');
            $table->dropIndex('provider_connections_workspace_provider_review_required_idx');

            $table->dropColumn([
                'connection_type',
                'consent_status',
                'consent_granted_at',
                'consent_last_checked_at',
                'consent_error_code',
                'consent_error_message',
                'verification_status',
                'migration_review_required',
                'migration_reviewed_at',
            ]);
        });
    }
};
