<?php

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

return new class extends Migration
{
    /**
     * 작업지시 담당자 피벗 테이블 (Work Order Assignees)
     * - 다중 담당자 지원
     * - 주 담당자 구분 (is_primary)
     */
    public function up(): void
    {
        if (Schema::hasTable('work_order_assignees')) {
            return; // 이미 존재하면 건너뜀
        }

        Schema::create('work_order_assignees', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('tenant_id')->comment('테넌트ID');
            $table->unsignedBigInteger('work_order_id')->comment('작업지시ID');
            $table->unsignedBigInteger('user_id')->comment('담당자ID');
            $table->boolean('is_primary')->default(false)->comment('주담당자 여부');
            $table->timestamps();

            // Indexes
            $table->unique(['work_order_id', 'user_id'], 'uq_work_order_assignees');
            $table->index(['tenant_id', 'work_order_id'], 'idx_wo_assignees_tenant_wo');
            $table->index(['tenant_id', 'user_id'], 'idx_wo_assignees_tenant_user');

            // Foreign keys
            $table->foreign('work_order_id')
                ->references('id')
                ->on('work_orders')
                ->onDelete('cascade');
        });
    }

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