<?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('equipment_inspections', function (Blueprint $table) {
            $table->string('inspection_cycle', 20)->default('daily')->after('equipment_id')
                ->comment('점검주기: daily/weekly/monthly/bimonthly/quarterly/semiannual');
        });

        // 기존 레코드를 daily로 설정
        DB::statement("UPDATE equipment_inspections SET inspection_cycle = 'daily' WHERE inspection_cycle = '' OR inspection_cycle IS NULL");

        Schema::table('equipment_inspections', function (Blueprint $table) {
            // 기존 유니크/인덱스 삭제
            $table->dropUnique('uq_inspection_month');
            $table->dropIndex('idx_inspection_ym');

            // cycle 포함 유니크/인덱스 추가
            $table->unique(['tenant_id', 'equipment_id', 'inspection_cycle', 'year_month'], 'uq_inspection_cycle_period');
            $table->index(['tenant_id', 'inspection_cycle', 'year_month'], 'idx_inspection_cycle_period');
        });
    }

    public function down(): void
    {
        Schema::table('equipment_inspections', function (Blueprint $table) {
            $table->dropIndex('idx_inspection_cycle_period');
            $table->dropUnique('uq_inspection_cycle_period');

            $table->unique(['tenant_id', 'equipment_id', 'year_month'], 'uq_inspection_month');
            $table->index(['tenant_id', 'year_month'], 'idx_inspection_ym');

            $table->dropColumn('inspection_cycle');
        });
    }
};
