<?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('fund_schedules', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('tenant_id')->comment('테넌트 ID');

            // 기본 정보
            $table->string('title', 200)->comment('일정명');
            $table->text('description')->nullable()->comment('설명');

            // 일정 유형: income(입금예정), expense(지급예정)
            $table->enum('schedule_type', ['income', 'expense'])->comment('일정유형: income=입금, expense=지급');

            // 일정 정보
            $table->date('scheduled_date')->comment('예정일');
            $table->decimal('amount', 18, 2)->default(0)->comment('금액');
            $table->string('currency', 3)->default('KRW')->comment('통화');

            // 관련 정보
            $table->unsignedBigInteger('related_bank_account_id')->nullable()->comment('관련 계좌 ID');
            $table->string('counterparty', 200)->nullable()->comment('거래상대방');
            $table->string('category', 50)->nullable()->comment('분류');

            // 상태: pending(예정), completed(완료), cancelled(취소)
            $table->enum('status', ['pending', 'completed', 'cancelled'])->default('pending')->comment('상태');

            // 반복 설정
            $table->boolean('is_recurring')->default(false)->comment('정기 여부');
            $table->string('recurrence_rule', 100)->nullable()->comment('반복 규칙 (daily, weekly, monthly, yearly)');
            $table->date('recurrence_end_date')->nullable()->comment('반복 종료일');

            // 완료 정보
            $table->date('completed_date')->nullable()->comment('실제 완료일');
            $table->decimal('completed_amount', 18, 2)->nullable()->comment('실제 완료 금액');

            // 추가 정보
            $table->text('memo')->nullable()->comment('메모');

            // 감사 필드
            $table->unsignedBigInteger('created_by')->nullable()->comment('생성자 ID');
            $table->unsignedBigInteger('updated_by')->nullable()->comment('수정자 ID');
            $table->unsignedBigInteger('deleted_by')->nullable()->comment('삭제자 ID');

            $table->timestamps();
            $table->softDeletes();

            // 인덱스
            $table->index('tenant_id', 'idx_fund_schedules_tenant');
            $table->index('scheduled_date', 'idx_fund_schedules_date');
            $table->index('schedule_type', 'idx_fund_schedules_type');
            $table->index('status', 'idx_fund_schedules_status');
            $table->index(['tenant_id', 'scheduled_date'], 'idx_fund_schedules_tenant_date');
            $table->index('deleted_at', 'idx_fund_schedules_deleted');
        });
    }

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