<?php

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

/**
 * Fix B-02/D-01: tambah unique constraint ke guest_customers.session_id.
 *
 * Sebelumnya hanya ->index(), sehingga updateOrCreate() tidak dijamin
 * atomic dan bisa menghasilkan duplikat row pada concurrent request.
 *
 * Perlu hapus duplikat terlebih dahulu (jika ada) sebelum menambah constraint.
 */
return new class extends Migration
{
    public function up(): void
    {
        // Hapus duplikat — pertahankan record terbaru per session_id
        DB::statement('
            DELETE g1 FROM guest_customers g1
            INNER JOIN guest_customers g2
            WHERE g1.id < g2.id AND g1.session_id = g2.session_id
        ');

        Schema::table('guest_customers', function (Blueprint $table) {
            // Hapus index lama, ganti dengan unique
            $table->dropIndex(['session_id']);
            $table->unique('session_id');
        });
    }

    public function down(): void
    {
        Schema::table('guest_customers', function (Blueprint $table) {
            $table->dropUnique(['session_id']);
            $table->index('session_id');
        });
    }
};
