<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // 알림 그룹 정의 (테넌트별 커스터마이징 가능)
        Schema::create('notification_setting_groups', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained()->cascadeOnDelete()->comment('테넌트 ID');
            $table->string('code', 50)->comment('그룹 코드 (notice, schedule, vendor 등)');
            $table->string('name', 100)->comment('그룹명 (공지 알림, 일정 알림 등)');
            $table->unsignedSmallInteger('sort_order')->default(0)->comment('정렬 순서');
            $table->boolean('is_active')->default(true)->comment('활성화 여부');
            $table->timestamps();

            $table->unique(['tenant_id', 'code']);
            $table->index(['tenant_id', 'is_active', 'sort_order']);
        });

        // 그룹-타입 매핑 (어떤 알림 타입이 어떤 그룹에 속하는지)
        Schema::create('notification_setting_group_items', function (Blueprint $table) {
            $table->id();
            $table->foreignId('group_id')->constrained('notification_setting_groups')->cascadeOnDelete()->comment('그룹 ID');
            $table->string('notification_type', 50)->comment('알림 타입 (notice, event, vat_report 등)');
            $table->string('label', 100)->comment('항목 라벨 (공지사항 알림, 이벤트 알림 등)');
            $table->unsignedSmallInteger('sort_order')->default(0)->comment('정렬 순서');
            $table->timestamps();

            $table->unique(['group_id', 'notification_type'], 'noti_grp_items_group_type_unique');
            $table->index(['group_id', 'sort_order'], 'noti_grp_items_group_sort_idx');
        });

        // 사용자별 그룹 활성화 상태
        Schema::create('notification_setting_group_states', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained()->cascadeOnDelete()->comment('테넌트 ID');
            $table->foreignId('user_id')->constrained()->cascadeOnDelete()->comment('사용자 ID');
            $table->string('group_code', 50)->comment('그룹 코드');
            $table->boolean('enabled')->default(true)->comment('그룹 전체 활성화 여부');
            $table->timestamps();

            $table->unique(['tenant_id', 'user_id', 'group_code'], 'noti_grp_states_tenant_user_group_unique');
            $table->index(['tenant_id', 'user_id'], 'noti_grp_states_tenant_user_idx');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('notification_setting_group_states');
        Schema::dropIfExists('notification_setting_group_items');
        Schema::dropIfExists('notification_setting_groups');
    }
};
