<?php

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

return new class extends Migration
{
    public function up(): void
    {
        if (! Schema::hasTable('audit_logs') || ! Schema::hasColumn('audit_logs', 'workspace_id')) {
            return;
        }

        $driver = DB::getDriverName();

        if ($driver === 'pgsql') {
            DB::statement(<<<'SQL'
                UPDATE audit_logs
                SET workspace_id = managed_environments.workspace_id
                FROM managed_environments
                WHERE audit_logs.managed_environment_id = managed_environments.id
                  AND audit_logs.managed_environment_id IS NOT NULL
                  AND audit_logs.workspace_id IS NULL
            SQL);

            return;
        }

        if ($driver === 'mysql') {
            DB::statement(<<<'SQL'
                UPDATE audit_logs
                JOIN managed_environments ON managed_environments.id = audit_logs.managed_environment_id
                SET audit_logs.workspace_id = managed_environments.workspace_id
                WHERE audit_logs.managed_environment_id IS NOT NULL
                  AND audit_logs.workspace_id IS NULL
            SQL);

            return;
        }

        DB::table('audit_logs')
            ->whereNotNull('managed_environment_id')
            ->whereNull('workspace_id')
            ->orderBy('id')
            ->chunkById(500, function ($rows): void {
                foreach ($rows as $row) {
                    $workspaceId = DB::table('managed_environments')
                        ->where('id', (int) $row->managed_environment_id)
                        ->value('workspace_id');

                    if ($workspaceId === null) {
                        continue;
                    }

                    DB::table('audit_logs')
                        ->where('id', (int) $row->id)
                        ->update(['workspace_id' => (int) $workspaceId]);
                }
            }, 'id');
    }

    public function down(): void
    {
        // Intentionally no-op; this migration repairs historical scope metadata.
    }
};
