<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class FinanceGroup extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'description',
        'min_amount',
        'max_amount',
        'is_active',
        'is_crypto_enabled',
        'badge_color',
        'created_by',
    ];

    protected $casts = [
        'min_amount' => 'decimal:2',
        'max_amount' => 'decimal:2',
        'is_active' => 'boolean',
        'is_crypto_enabled' => 'boolean',
    ];

    /**
     * Get finance users in this group
     */
    public function financeUsers()
    {
        return $this->hasMany(FinanceUser::class);
    }

    /**
     * Get bank accounts in this group
     */
    public function bankAccounts()
    {
        return $this->hasMany(BankAccount::class);
    }

    /**
     * Get crypto accounts in this group.
     */
    public function cryptoAccounts()
    {
        return $this->hasMany(CryptoAccount::class);
    }

    /**
     * Get active bank accounts in this group
     */
    public function activeBankAccounts()
    {
        return $this->hasMany(BankAccount::class)->where('is_active', true);
    }

    /**
     * Per-site min/max overrides for this finance group.
     */
    public function siteLimits()
    {
        return $this->hasMany(FinanceGroupSiteLimit::class);
    }

    /**
     * Per-site active/passive overrides for this finance group.
     */
    public function siteStatuses()
    {
        return $this->hasMany(FinanceGroupSiteStatus::class);
    }

    /**
     * Get transactions assigned to this group
     */
    public function transactions()
    {
        return $this->hasMany(Transaction::class);
    }

    /**
     * Get the user who created this finance group
     */
    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /**
     * Scope a query to only include active finance groups
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * Effective active state for a specific site.
     */
    public function isActiveForSite(?int $siteId): bool
    {
        if (!$siteId) {
            return (bool) $this->is_active;
        }

        $siteStatus = $this->relationLoaded('siteStatuses')
            ? $this->siteStatuses->firstWhere('site_id', $siteId)
            : $this->siteStatuses()->where('site_id', $siteId)->first();

        if (!$siteStatus) {
            return (bool) $this->is_active;
        }

        return (bool) $siteStatus->is_active;
    }

    /**
     * Check if amount is within this group's range
     */
    public function isAmountInRange($amount)
    {
        return $amount >= $this->min_amount && $amount <= $this->max_amount;
    }

    /**
     * Resolve site-specific min/max.
     *
     * @return array{min: float, max: float}|null
     */
    public function getEffectiveLimitsForSite(?int $siteId): ?array
    {
        if (!$siteId) {
            return null;
        }

        $siteLimit = $this->relationLoaded('siteLimits')
            ? $this->siteLimits->firstWhere('site_id', $siteId)
            : $this->siteLimits()->where('site_id', $siteId)->first();

        if (!$siteLimit) {
            return null;
        }

        return [
            'min' => (float) $siteLimit->min_amount,
            'max' => (float) $siteLimit->max_amount,
        ];
    }

    /**
     * Check amount against effective site-specific limits.
     */
    public function isAmountInRangeForSite($amount, ?int $siteId): bool
    {
        $limits = $this->getEffectiveLimitsForSite($siteId);
        if (!$limits) {
            return false;
        }

        $value = (float) $amount;

        return $value >= $limits['min'] && $value <= $limits['max'];
    }

}
