<?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
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // material_type 컬럼이 없을 때만 추가
        if (! Schema::hasColumn('materials', 'material_type')) {
            Schema::table('materials', function (Blueprint $table) {
                // material_type 컬럼 추가 (SM=부자재, RM=원자재, CS=소모품)
                $table->string('material_type', 10)
                    ->nullable()
                    ->after('category_id')
                    ->comment('자재 타입: SM=부자재, RM=원자재, CS=소모품');
            });
        }

        // 인덱스가 없을 때만 추가
        $indexes = collect(DB::select('SHOW INDEX FROM materials'))
            ->pluck('Key_name')
            ->toArray();

        if (! in_array('materials_material_type_index', $indexes)) {
            Schema::table('materials', function (Blueprint $table) {
                $table->index('material_type');
            });
        }

        // 기존 데이터 업데이트 (options 컬럼이 없으므로 기본값 'SM' 설정)
        DB::statement("
            UPDATE materials
            SET material_type = 'SM'
            WHERE deleted_at IS NULL
            AND material_type IS NULL
        ");

        // 모든 자재에 타입이 설정되었으므로 NOT NULL로 변경
        Schema::table('materials', function (Blueprint $table) {
            $table->string('material_type', 10)->default('SM')->nullable(false)->change();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('materials', function (Blueprint $table) {
            $table->dropIndex(['material_type']);
            $table->dropColumn('material_type');
        });
    }
};
