<?php

namespace App\Models\Barobill;

use App\Models\Tenants\Tenant;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * 바로빌 카드 사용내역 모델
 */
class CardTransaction extends Model
{
    protected $table = 'barobill_card_transactions';

    protected $fillable = [
        'tenant_id',
        'card_num',
        'card_company',
        'card_company_name',
        'use_dt',
        'use_date',
        'use_time',
        'approval_num',
        'approval_type',
        'approval_amount',
        'tax',
        'service_charge',
        'payment_plan',
        'currency_code',
        'merchant_name',
        'merchant_biz_num',
        'merchant_addr',
        'merchant_ceo',
        'merchant_biz_type',
        'merchant_tel',
        'memo',
        'use_key',
        'account_code',
        'account_name',
        'deduction_type',
        'evidence_name',
        'description',
        'modified_supply_amount',
        'modified_tax',
        'is_manual',
    ];

    protected $casts = [
        'approval_amount' => 'decimal:2',
        'tax' => 'decimal:2',
        'service_charge' => 'decimal:2',
        'modified_supply_amount' => 'decimal:2',
        'modified_tax' => 'decimal:2',
        'is_manual' => 'boolean',
    ];

    /**
     * 테넌트 관계
     */
    public function tenant(): BelongsTo
    {
        return $this->belongsTo(Tenant::class);
    }

    /**
     * 거래 고유 키 생성 (매칭용)
     */
    public function getUniqueKeyAttribute(): string
    {
        return implode('|', [
            $this->card_num,
            $this->use_dt,
            $this->approval_num,
            (int) $this->approval_amount,
        ]);
    }

    /**
     * 바로빌 로그 데이터로부터 고유 키 생성 (정적 메서드)
     */
    public static function generateUniqueKey(array $log): string
    {
        return implode('|', [
            $log['cardNum'] ?? '',
            $log['useDt'] ?? '',
            $log['approvalNum'] ?? '',
            (int) ($log['approvalAmount'] ?? 0),
        ]);
    }

    /**
     * 테넌트별 거래 내역 조회 (기간별)
     */
    public static function getByDateRange(int $tenantId, string $startDate, string $endDate, ?string $cardNum = null)
    {
        $query = self::where('tenant_id', $tenantId)
            ->whereBetween('use_date', [$startDate, $endDate])
            ->orderBy('use_date', 'desc')
            ->orderBy('use_time', 'desc');

        if ($cardNum) {
            $query->where('card_num', $cardNum);
        }

        return $query->get()->keyBy(fn ($item) => $item->unique_key);
    }
}
