<?php

namespace App\Services;

use App\Models\Account;
use App\Models\Transaction;
use Carbon\Carbon;
use Illuminate\Validation\ValidationException;

class TransactionLimitGuard
{
    public static function enforce(Account $account, float $amount): void
    {
        // =============================
        // 1. Per-transaction limit
        // =============================
        if ($amount > $account->per_transaction_limit) {
            throw ValidationException::withMessages([
                'amount' => 'Transaction declined: Amount exceeds per-transaction limit.',
            ]);
        }

        // =============================
        // 2. Daily limit
        // =============================
        $dailyUsed = Transaction::where('account_id', $account->id)
            ->whereDate('created_at', Carbon::today())
            ->sum('amount');

        if (($dailyUsed + $amount) > $account->daily_transaction_limit) {
            throw ValidationException::withMessages([
                'amount' => 'Transaction declined: Daily transaction limit exceeded.',
            ]);
        }

        // =============================
        // 3. Monthly limit
        // =============================
        $monthlyUsed = Transaction::where('account_id', $account->id)
            ->whereBetween('created_at', [
                Carbon::now()->startOfMonth(),
                Carbon::now()->endOfMonth(),
            ])
            ->sum('amount');

        if (($monthlyUsed + $amount) > $account->monthly_transaction_limit) {
            throw ValidationException::withMessages([
                'amount' => 'Transaction declined: Monthly transaction limit exceeded.',
            ]);
        }
    }
}
