<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('esign_contracts', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained()->onDelete('cascade')->comment('테넌트 ID');
            $table->string('contract_code', 50)->unique()->comment('계약 코드');
            $table->string('title', 200)->comment('계약 제목');
            $table->text('description')->nullable()->comment('계약 설명');
            $table->enum('sign_order_type', ['counterpart_first', 'creator_first'])->default('counterpart_first')->comment('서명 순서 (counterpart_first: 상대방 먼저, creator_first: 작성자 먼저)');
            $table->string('original_file_path', 500)->nullable()->comment('원본 PDF 파일 경로');
            $table->string('original_file_name', 255)->nullable()->comment('원본 파일명');
            $table->string('original_file_hash', 64)->nullable()->comment('원본 파일 SHA-256 해시');
            $table->unsignedBigInteger('original_file_size')->nullable()->comment('원본 파일 크기 (bytes)');
            $table->string('signed_file_path', 500)->nullable()->comment('서명 완료 PDF 파일 경로');
            $table->string('signed_file_hash', 64)->nullable()->comment('서명 완료 파일 SHA-256 해시');
            $table->enum('status', ['draft', 'pending', 'partially_signed', 'completed', 'expired', 'cancelled', 'rejected'])->default('draft')->comment('계약 상태');
            $table->timestamp('expires_at')->nullable()->comment('계약 만료일시');
            $table->timestamp('completed_at')->nullable()->comment('계약 완료일시');
            $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->index('tenant_id', 'idx_esign_contracts_tenant');
            $table->index('status', 'idx_esign_contracts_status');
            $table->index('expires_at', 'idx_esign_contracts_expires');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('esign_contracts');
    }
};
