<?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
    {
        Schema::table('users', function (Blueprint $table) {
            if (!Schema::hasColumn('users', 'has_all_mariachi_groups')) {
                $table->boolean('has_all_mariachi_groups')->default(false)->after('organization_id');
            }
        });

        Schema::create('mariachi_group_user', function (Blueprint $table) {
            $table->id();
            $table->foreignId('mariachi_group_id')->constrained()->cascadeOnDelete();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->timestamps();

            $table->unique(['mariachi_group_id', 'user_id']);
            $table->index(['user_id', 'mariachi_group_id']);
        });

        DB::table('users')
            ->whereIn('role', ['CLIENT', 'OWNER_STAFF'])
            ->update(['has_all_mariachi_groups' => true]);
    }

    public function down(): void
    {
        Schema::dropIfExists('mariachi_group_user');

        Schema::table('users', function (Blueprint $table) {
            if (Schema::hasColumn('users', 'has_all_mariachi_groups')) {
                $table->dropColumn('has_all_mariachi_groups');
            }
        });
    }
};
