<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * 통합 검사 테이블 생성 및 레거시 테이블 정리
     * - inspections: IQC/PQC/FQC 통합 관리
     * - material_receipts → item_receipts 이름 변경
     * - 삭제: material_inspections, material_inspection_items
     */
    public function up(): void
    {
        // 1. 통합 검사 테이블 생성
        Schema::create('inspections', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('tenant_id')->comment('테넌트 ID');

            // 인덱스 컬럼 (검색/필터용)
            $table->string('inspection_no', 30)->comment('검사번호');
            $table->enum('inspection_type', ['IQC', 'PQC', 'FQC'])->comment('검사유형: IQC(수입검사), PQC(공정검사), FQC(최종검사)');
            $table->enum('status', ['waiting', 'in_progress', 'completed'])->default('waiting')->comment('상태');
            $table->enum('result', ['pass', 'fail'])->nullable()->comment('판정결과');
            $table->date('request_date')->comment('검사요청일');
            $table->date('inspection_date')->nullable()->comment('검사일');
            $table->unsignedBigInteger('item_id')->nullable()->comment('품목 ID (items FK)');
            $table->string('lot_no', 50)->comment('LOT번호');
            $table->unsignedBigInteger('inspector_id')->nullable()->comment('검사자 ID (users FK)');

            // JSON 컬럼 (비검색 데이터)
            $table->json('meta')->nullable()->comment('메타정보: process_name, quantity, unit, supplier_name, manufacturer_name 등');
            $table->json('items')->nullable()->comment('검사항목 배열: [{name, type, spec, unit, result, measured_value, judgment}]');
            $table->json('attachments')->nullable()->comment('첨부파일: [{id, file_name, file_url, file_type, uploaded_at}]');
            $table->json('extra')->nullable()->comment('추가정보: remarks, opinion, approver_name 등');

            // 감사 컬럼
            $table->unsignedBigInteger('created_by')->comment('생성자');
            $table->unsignedBigInteger('updated_by')->nullable()->comment('수정자');
            $table->unsignedBigInteger('deleted_by')->nullable()->comment('삭제자');
            $table->timestamps();
            $table->softDeletes();

            // 인덱스
            $table->unique(['tenant_id', 'inspection_no'], 'inspections_tenant_no_unique');
            $table->index('tenant_id', 'inspections_tenant_idx');
            $table->index('inspection_type', 'inspections_type_idx');
            $table->index('status', 'inspections_status_idx');
            $table->index('result', 'inspections_result_idx');
            $table->index('request_date', 'inspections_request_date_idx');
            $table->index('inspection_date', 'inspections_inspection_date_idx');
            $table->index('item_id', 'inspections_item_idx');
            $table->index('lot_no', 'inspections_lot_idx');
            $table->index('inspector_id', 'inspections_inspector_idx');
            $table->index(['tenant_id', 'inspection_type', 'status'], 'inspections_tenant_type_status_idx');
        });

        // 2. material_receipts → item_receipts 이름 변경
        Schema::rename('material_receipts', 'item_receipts');

        // 3. 레거시 검사 테이블 삭제
        Schema::dropIfExists('material_inspection_items');
        Schema::dropIfExists('material_inspections');
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        // 1. 통합 테이블 삭제
        Schema::dropIfExists('inspections');

        // 2. item_receipts → material_receipts 이름 복원
        Schema::rename('item_receipts', 'material_receipts');

        // 3. 레거시 검사 테이블 복원
        Schema::create('material_inspections', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('receipt_id');
            $table->unsignedBigInteger('tenant_id');
            $table->date('inspection_date');
            $table->string('inspector_name', 50)->nullable();
            $table->string('approver_name', 50)->nullable();
            $table->string('judgment_code', 30);
            $table->string('status_code', 30);
            $table->text('result_file_path')->nullable();
            $table->text('remarks')->nullable();
            $table->unsignedBigInteger('created_by');
            $table->unsignedBigInteger('updated_by')->nullable();
            $table->timestamps();
            $table->softDeletes();
            $table->unsignedBigInteger('deleted_by')->nullable();

            $table->index('receipt_id');
        });

        Schema::create('material_inspection_items', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('inspection_id');
            $table->string('item_name', 100);
            $table->char('is_checked', 1)->default('N');
            $table->unsignedBigInteger('created_by');
            $table->unsignedBigInteger('updated_by')->nullable();
            $table->timestamps();
            $table->softDeletes();
            $table->unsignedBigInteger('deleted_by')->nullable();

            $table->index('inspection_id');
        });
    }
};
