<?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('barobill_bank_transactions', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained()->onDelete('cascade');
            $table->string('bank_account_num', 50)->comment('계좌번호');
            $table->string('bank_code', 10)->nullable()->comment('은행코드');
            $table->string('bank_name', 50)->nullable()->comment('은행명');
            $table->string('trans_date', 8)->comment('거래일 (YYYYMMDD)');
            $table->string('trans_time', 6)->nullable()->comment('거래시간 (HHMMSS)');
            $table->string('trans_dt', 20)->comment('거래일시 원본 (YYYYMMDDHHMMSS)');
            $table->decimal('deposit', 18, 2)->default(0)->comment('입금액');
            $table->decimal('withdraw', 18, 2)->default(0)->comment('출금액');
            $table->decimal('balance', 18, 2)->default(0)->comment('잔액');
            $table->string('summary', 255)->nullable()->comment('적요');
            $table->string('cast', 100)->nullable()->comment('상대방');
            $table->string('memo', 255)->nullable()->comment('메모');
            $table->string('trans_office', 100)->nullable()->comment('거래점');
            $table->string('account_code', 50)->nullable()->comment('계정과목 코드');
            $table->string('account_name', 100)->nullable()->comment('계정과목 명');
            $table->timestamps();

            // 복합 유니크 인덱스: 같은 거래는 중복 저장 방지
            $table->unique(
                ['tenant_id', 'bank_account_num', 'trans_dt', 'deposit', 'withdraw', 'balance'],
                'barobill_bank_trans_unique'
            );

            // 조회용 인덱스
            $table->index(['tenant_id', 'trans_date'], 'bb_trans_tenant_date_idx');
            $table->index(['tenant_id', 'bank_account_num', 'trans_date'], 'bb_trans_tenant_acct_date_idx');
        });
    }

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