<?php

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

return new class extends Migration
{
    public function up(): void
    {
        // Teams table - THE CORE ENTITY
        Schema::create('teams', function (Blueprint $table) {
            $table->id();
            $table->foreignId('business_id')->constrained()->onDelete('cascade');
            $table->string('name');
            $table->string('description')->nullable();
            $table->enum('status', ['active', 'inactive', 'archived'])->default('active');
            $table->integer('member_count')->default(0);
            $table->timestamps();
            $table->softDeletes();

            $table->index('business_id');
            $table->index('status');
        });

        // Team members pivot with roles and permissions
        Schema::create('team_user', function (Blueprint $table) {
            $table->id();
            $table->foreignId('team_id')->constrained()->onDelete('cascade');
            $table->foreignId('user_id')->constrained()->onDelete('cascade');
            $table->foreignId('role_id')->nullable()->constrained('roles')->onDelete('set null');
            $table->json('custom_permissions')->nullable(); // Team-specific permissions
            $table->enum('status', ['active', 'inactive', 'pending_invitation'])->default('pending_invitation');
            $table->timestamp('invited_at')->nullable();
            $table->timestamp('joined_at')->nullable();
            $table->timestamps();
            $table->softDeletes();

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

        // Enhanced business_staff to reference team
        Schema::table('business_staff', function (Blueprint $table) {
            if (!Schema::hasColumn('business_staff', 'team_id')) {
                $table->foreignId('team_id')->nullable()->after('business_id')->constrained('teams')->onDelete('set null');
            }
        });
    }

    public function down(): void
    {
        Schema::table('business_staff', function (Blueprint $table) {
            if (Schema::hasColumn('business_staff', 'team_id')) {
                $table->dropForeignKeyIfExists(['team_id']);
                $table->dropColumn('team_id');
            }
        });

        Schema::dropIfExists('team_user');
        Schema::dropIfExists('teams');
    }
};

