<?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
{
    public function up(): void
    {
        Schema::table('materials', function (Blueprint $table) {
            // category_id
            if (! Schema::hasColumn('materials', 'category_id')) {
                $table->unsignedBigInteger('category_id')
                    ->nullable()
                    ->after('tenant_id')
                    ->comment('카테고리 ID')
                    ->index();
            }

            // item_name
            if (! Schema::hasColumn('materials', 'item_name')) {
                $table->string('item_name', 255)
                    ->nullable()
                    ->after('name')
                    ->comment('품목명 (자재명+규격정보)');
            }
        });

        // 필요 시 FK RAW SQL로 추가(선택)
        // try {
        //     DB::statement('ALTER TABLE materials
        //         ADD CONSTRAINT materials_category_id_foreign
        //         FOREIGN KEY (category_id) REFERENCES categories(id)
        //         ON DELETE SET NULL');
        // } catch (\Throwable $e) {}
    }

    public function down(): void
    {
        // FK 제거 시도
        try {
            DB::statement('ALTER TABLE materials DROP FOREIGN KEY materials_category_id_foreign');
        } catch (\Throwable $e) {
        }

        // 컬럼 제거
        try {
            DB::statement('ALTER TABLE materials DROP COLUMN category_id');
        } catch (\Throwable $e) {
        }
        try {
            DB::statement('ALTER TABLE materials DROP COLUMN item_name');
        } catch (\Throwable $e) {
        }
    }
};
