<?php

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
    {
        // 1. Drop old constraint
        DB::statement("ALTER TABLE participants DROP CONSTRAINT IF EXISTS participants_membership_type_check");

        // 2. Reset any existing membership_type values to null (clean slate)
        DB::table('participants')->whereNotNull('membership_type')->update(['membership_type' => null]);

        // 3. Add new constraint: member or non_member only
        DB::statement("ALTER TABLE participants ADD CONSTRAINT participants_membership_type_check CHECK ((membership_type IS NULL) OR (membership_type IN ('member', 'non_member')))");

        // 4. Add membership_id column (club membership number)
        Schema::table('participants', function (Blueprint $table) {
            $table->string('membership_id', 50)->nullable()->after('membership_type');
        });

        // 5. Unique membership_id per branch (can't reuse same club ID within a branch)
        DB::statement("CREATE UNIQUE INDEX participants_branch_membership_id_unique ON participants (branch_id, membership_id) WHERE membership_id IS NOT NULL AND deleted_at IS NULL");
    }

    public function down(): void
    {
        DB::statement("DROP INDEX IF EXISTS participants_branch_membership_id_unique");

        Schema::table('participants', function (Blueprint $table) {
            $table->dropColumn('membership_id');
        });

        DB::statement("ALTER TABLE participants DROP CONSTRAINT IF EXISTS participants_membership_type_check");
        DB::statement("ALTER TABLE participants ADD CONSTRAINT participants_membership_type_check CHECK ((membership_type IS NULL) OR ((membership_type)::text = ANY ((ARRAY['basic'::character varying, 'silver'::character varying, 'gold'::character varying, 'platinum'::character varying, 'custom'::character varying])::text[])))");
    }
};
