<?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('user_invitations', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained()->cascadeOnDelete()->comment('테넌트 ID');
            $table->string('email', 255)->comment('초대 대상 이메일');
            $table->foreignId('role_id')->nullable()->constrained('roles')->nullOnDelete()->comment('부여할 역할 ID');
            $table->text('message')->nullable()->comment('초대 메시지');
            $table->string('token', 64)->unique()->comment('초대 토큰');
            $table->string('status', 20)->default('pending')->index()->comment('상태 (pending/accepted/expired/cancelled)');
            $table->foreignId('invited_by')->constrained('users')->cascadeOnDelete()->comment('초대한 사용자 ID');
            $table->timestamp('expires_at')->comment('만료 일시');
            $table->timestamp('accepted_at')->nullable()->comment('수락 일시');
            $table->timestamps();

            // 복합 인덱스: 테넌트별 이메일 검색
            $table->index(['tenant_id', 'email']);
            // 복합 인덱스: 상태별 만료 일시 (스케줄러용)
            $table->index(['status', 'expires_at']);
        });
    }

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