<?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('bank_transactions', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained()->cascadeOnDelete();
            $table->foreignId('bank_account_id')->constrained('bank_accounts')->cascadeOnDelete();

            // 거래 정보
            $table->string('transaction_type', 20)->comment('거래유형: deposit(입금), withdrawal(출금), transfer(이체)');
            $table->decimal('amount', 18, 2)->comment('거래금액');
            $table->decimal('balance_after', 18, 2)->comment('거래 후 잔액');

            // 날짜
            $table->date('transaction_date')->comment('거래일자');
            $table->time('transaction_time')->nullable()->comment('거래시간');

            // 상세 정보
            $table->string('description', 255)->nullable()->comment('적요');
            $table->string('counterparty', 100)->nullable()->comment('거래상대방');
            $table->string('reference_number', 100)->nullable()->comment('참조번호');

            // 분류
            $table->string('category', 50)->nullable()->comment('거래분류');
            $table->foreignId('related_order_id')->nullable()->comment('관련 주문 ID');
            $table->foreignId('related_payment_id')->nullable()->comment('관련 결제 ID');

            // 상태
            $table->boolean('is_reconciled')->default(false)->comment('대사완료 여부');
            $table->timestamp('reconciled_at')->nullable()->comment('대사완료 일시');

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

            // 감사 필드
            $table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
            $table->foreignId('updated_by')->nullable()->constrained('users')->nullOnDelete();
            $table->foreignId('deleted_by')->nullable()->constrained('users')->nullOnDelete();

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

            // 인덱스
            $table->index('tenant_id', 'idx_bank_transactions_tenant');
            $table->index('bank_account_id', 'idx_bank_transactions_account');
            $table->index('transaction_date', 'idx_bank_transactions_date');
            $table->index('transaction_type', 'idx_bank_transactions_type');
            $table->index('is_reconciled', 'idx_bank_transactions_reconciled');
            $table->index('deleted_at', 'idx_bank_transactions_deleted');
            $table->index(['tenant_id', 'transaction_date'], 'idx_bank_transactions_tenant_date');
        });
    }

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