<?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_signers', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained()->onDelete('cascade')->comment('테넌트 ID');
            $table->foreignId('contract_id')->constrained('esign_contracts')->onDelete('cascade')->comment('계약 ID');
            $table->enum('role', ['creator', 'counterpart'])->comment('서명자 역할');
            $table->tinyInteger('sign_order')->default(1)->comment('서명 순서');
            $table->string('name', 100)->comment('서명자 이름');
            $table->string('email', 255)->comment('서명자 이메일');
            $table->string('phone', 20)->nullable()->comment('서명자 전화번호');
            $table->string('access_token', 128)->unique()->comment('서명 접근 토큰');
            $table->timestamp('token_expires_at')->nullable()->comment('토큰 만료일시');
            $table->string('otp_code', 6)->nullable()->comment('OTP 인증코드');
            $table->timestamp('otp_expires_at')->nullable()->comment('OTP 만료일시');
            $table->tinyInteger('otp_attempts')->default(0)->comment('OTP 시도 횟수');
            $table->timestamp('auth_verified_at')->nullable()->comment('본인인증 완료일시');
            $table->string('signature_image_path', 500)->nullable()->comment('서명 이미지 경로');
            $table->timestamp('signed_at')->nullable()->comment('서명 완료일시');
            $table->timestamp('consent_agreed_at')->nullable()->comment('동의 일시');
            $table->string('sign_ip_address', 45)->nullable()->comment('서명 시 IP 주소');
            $table->string('sign_user_agent', 500)->nullable()->comment('서명 시 User Agent');
            $table->enum('status', ['waiting', 'notified', 'authenticated', 'signed', 'rejected'])->default('waiting')->comment('서명자 상태');
            $table->text('rejected_reason')->nullable()->comment('거절 사유');
            $table->timestamps();

            $table->index('tenant_id', 'idx_esign_signers_tenant');
            $table->index('contract_id', 'idx_esign_signers_contract');
            $table->index('status', 'idx_esign_signers_status');
        });
    }

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