<?php

namespace App\Models\Finance;

use App\Models\Tenants\Tenant;
use App\Traits\BelongsToTenant;
use App\Traits\ModelTrait;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * 은행 계좌 모델
 */
class BankAccount extends Model
{
    use BelongsToTenant, ModelTrait, SoftDeletes;

    protected $fillable = [
        'tenant_id',
        'bank_code',
        'bank_name',
        'account_number',
        'account_holder',
        'account_name',
        'account_type',
        'balance',
        'currency',
        'opened_at',
        'last_transaction_at',
        'branch_name',
        'memo',
        'status',
        'assigned_user_id',
        'is_primary',
        'sort_order',
        'created_by',
        'updated_by',
        'deleted_by',
    ];

    protected $hidden = [
        'created_by',
        'updated_by',
        'deleted_by',
        'deleted_at',
    ];

    protected $casts = [
        'balance' => 'decimal:2',
        'is_primary' => 'boolean',
        'opened_at' => 'date',
        'last_transaction_at' => 'datetime',
    ];

    // ============================================================
    // 관계 정의
    // ============================================================

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

    /**
     * 거래내역
     */
    public function transactions(): HasMany
    {
        return $this->hasMany(BankTransaction::class, 'bank_account_id');
    }

    // ============================================================
    // Accessors
    // ============================================================

    /**
     * 포맷된 잔액
     */
    public function getFormattedBalanceAttribute(): string
    {
        $amount = abs($this->balance);

        if ($amount >= 100000000) {
            return number_format($amount / 100000000, 1).'억원';
        } elseif ($amount >= 10000000) {
            return number_format($amount / 10000000, 0).'천만원';
        } elseif ($amount >= 10000) {
            return number_format($amount / 10000, 0).'만원';
        }

        return number_format($amount).'원';
    }

    /**
     * 포맷된 계좌번호 (마스킹)
     */
    public function getMaskedAccountNumberAttribute(): string
    {
        $number = $this->account_number;
        if (strlen($number) <= 6) {
            return $number;
        }

        return substr($number, 0, 3).'-***-'.substr($number, -4);
    }

    // ============================================================
    // Scopes
    // ============================================================

    /**
     * 활성 계좌만 (status = 'active')
     */
    public function scopeActive($query)
    {
        return $query->where('status', 'active');
    }

    /**
     * 대표 계좌만
     */
    public function scopePrimary($query)
    {
        return $query->where('is_primary', true);
    }

    /**
     * 은행별 필터
     */
    public function scopeByBank($query, string $bankName)
    {
        return $query->where('bank_name', $bankName);
    }

    /**
     * 예금종류별 필터
     */
    public function scopeByType($query, string $accountType)
    {
        return $query->where('account_type', $accountType);
    }

    /**
     * 정렬 순서
     */
    public function scopeOrdered($query)
    {
        return $query->orderBy('sort_order')->orderBy('bank_name');
    }

    // ============================================================
    // 메서드
    // ============================================================

    /**
     * 잔액 업데이트
     */
    public function updateBalance(float $newBalance): void
    {
        $this->update([
            'balance' => $newBalance,
            'last_transaction_at' => now(),
        ]);
    }

    /**
     * 활성 상태 여부
     */
    public function isActive(): bool
    {
        return $this->status === 'active';
    }
}
