<?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('approvals', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained()->onDelete('cascade')->comment('테넌트 ID');
            $table->string('document_number', 50)->comment('문서번호');
            $table->foreignId('form_id')->constrained('approval_forms')->onDelete('restrict')->comment('결재 양식 ID');
            $table->string('title', 200)->comment('제목');
            $table->json('content')->comment('양식 데이터');
            $table->string('status', 20)->default('draft')->comment('상태: draft/pending/approved/rejected/cancelled');
            $table->foreignId('drafter_id')->constrained('users')->onDelete('restrict')->comment('기안자');
            $table->timestamp('drafted_at')->nullable()->comment('기안일시');
            $table->timestamp('completed_at')->nullable()->comment('완료일시');
            $table->integer('current_step')->default(0)->comment('현재 결재 단계');
            $table->json('attachments')->nullable()->comment('첨부파일 IDs');
            $table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete()->comment('생성자');
            $table->foreignId('updated_by')->nullable()->constrained('users')->nullOnDelete()->comment('수정자');
            $table->foreignId('deleted_by')->nullable()->constrained('users')->nullOnDelete()->comment('삭제자');
            $table->softDeletes();
            $table->timestamps();

            $table->unique(['tenant_id', 'document_number'], 'uk_tenant_document');
            $table->index(['tenant_id', 'status'], 'idx_tenant_status');
            $table->index('drafter_id', 'idx_drafter');
        });
    }

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