<?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_card_transactions', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained()->onDelete('cascade');
            $table->string('card_num', 50)->comment('카드번호');
            $table->string('card_company', 10)->nullable()->comment('카드사 코드');
            $table->string('card_company_name', 50)->nullable()->comment('카드사명');
            $table->string('use_dt', 20)->comment('사용일시 원본 (YYYYMMDDHHMMSS)');
            $table->string('use_date', 8)->comment('사용일 (YYYYMMDD)');
            $table->string('use_time', 6)->nullable()->comment('사용시간 (HHMMSS)');
            $table->string('approval_num', 50)->nullable()->comment('승인번호');
            $table->string('approval_type', 10)->nullable()->comment('승인유형 (1=승인, 2=취소)');
            $table->decimal('approval_amount', 18, 2)->default(0)->comment('승인금액');
            $table->decimal('tax', 18, 2)->default(0)->comment('부가세');
            $table->decimal('service_charge', 18, 2)->default(0)->comment('봉사료');
            $table->string('payment_plan', 10)->nullable()->comment('할부개월수');
            $table->string('currency_code', 10)->default('KRW')->comment('통화코드');
            $table->string('merchant_name', 255)->nullable()->comment('가맹점명');
            $table->string('merchant_biz_num', 20)->nullable()->comment('가맹점 사업자번호');
            $table->string('merchant_addr', 255)->nullable()->comment('가맹점 주소');
            $table->string('merchant_ceo', 100)->nullable()->comment('가맹점 대표자');
            $table->string('merchant_biz_type', 100)->nullable()->comment('가맹점 업종');
            $table->string('merchant_tel', 50)->nullable()->comment('가맹점 전화번호');
            $table->string('memo', 255)->nullable()->comment('메모');
            $table->string('use_key', 100)->nullable()->comment('사용키');
            $table->string('account_code', 50)->nullable()->comment('계정과목 코드');
            $table->string('account_name', 100)->nullable()->comment('계정과목 명');
            $table->timestamps();

            // 복합 유니크 인덱스: 같은 거래는 중복 저장 방지
            $table->unique(
                ['tenant_id', 'card_num', 'use_dt', 'approval_num', 'approval_amount'],
                'bb_card_trans_unique'
            );

            // 조회용 인덱스
            $table->index(['tenant_id', 'use_date'], 'bb_card_trans_tenant_date_idx');
            $table->index(['tenant_id', 'card_num', 'use_date'], 'bb_card_trans_tenant_card_date_idx');
        });
    }

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