<?php

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

return new class extends Migration
{
    /**
     * 작업지시 테이블 (Production Work Orders)
     */
    public function up(): void
    {
        Schema::create('work_orders', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('tenant_id')->comment('테넌트ID');
            $table->string('work_order_no', 50)->comment('작업지시번호');
            $table->unsignedBigInteger('sales_order_id')->nullable()->comment('수주ID');
            $table->string('project_name', 200)->nullable()->comment('프로젝트명');
            $table->string('process_type', 30)->comment('공정유형: screen/slat/bending');
            $table->string('status', 30)->default('unassigned')->comment('상태: unassigned/pending/waiting/in_progress/completed/shipped');
            $table->unsignedBigInteger('assignee_id')->nullable()->comment('담당자ID');
            $table->unsignedBigInteger('team_id')->nullable()->comment('팀ID');
            $table->date('scheduled_date')->nullable()->comment('예정일');
            $table->timestamp('started_at')->nullable()->comment('작업시작일시');
            $table->timestamp('completed_at')->nullable()->comment('작업완료일시');
            $table->timestamp('shipped_at')->nullable()->comment('출하일시');
            $table->text('memo')->nullable()->comment('메모');
            $table->boolean('is_active')->default(true)->comment('활성여부');
            $table->unsignedBigInteger('created_by')->nullable()->comment('생성자');
            $table->unsignedBigInteger('updated_by')->nullable()->comment('수정자');
            $table->timestamps();
            $table->softDeletes();

            // Indexes
            $table->unique(['tenant_id', 'work_order_no'], 'uq_work_orders_tenant_no');
            $table->index(['tenant_id', 'status'], 'idx_work_orders_tenant_status');
            $table->index(['tenant_id', 'process_type'], 'idx_work_orders_tenant_process');
            $table->index(['tenant_id', 'assignee_id'], 'idx_work_orders_tenant_assignee');
            $table->index(['tenant_id', 'scheduled_date'], 'idx_work_orders_tenant_scheduled');
            $table->index(['tenant_id', 'is_active'], 'idx_work_orders_tenant_active');
        });
    }

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