<?php

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

return new class extends Migration
{
    public function up(): void
    {
        $driver = DB::getDriverName();

        if ($driver === 'pgsql') {
            DB::statement(<<<'SQL'
                UPDATE addresses
                SET is_primary = true
                WHERE id IN (
                    SELECT DISTINCT ON (source_id) id
                    FROM addresses
                    WHERE source = 'client'
                      AND deleted_at IS NULL
                    ORDER BY source_id, is_primary DESC, id ASC
                )
            SQL);

            return;
        }

        if ($driver === 'mysql') {
            DB::statement(<<<'SQL'
                UPDATE addresses a
                JOIN (
                    SELECT MIN(id) AS id
                    FROM addresses
                    WHERE source = 'client'
                      AND deleted_at IS NULL
                    GROUP BY source_id
                ) first_address ON first_address.id = a.id
                SET a.is_primary = true
            SQL);
        }
    }

    public function down(): void
    {
        // Data backfill only. Do not unset primary addresses on rollback.
    }
};
