<?php

namespace App\Services;

use App\Models\User;
use App\Models\Transaction;
use App\Models\TransactionAllocation;
use Illuminate\Validation\ValidationException;

class AllocationService
{
    /**
     * Create allocation with validation.
     */
    public function allocate(
        Transaction $transaction,
        User $debtor,
        User $creditor,
        float $amount,
        ?string $notes = null
    ): TransactionAllocation {
        if ($transaction->status !== 'SETTLED') {
            throw ValidationException::withMessages([
                'transaction' => ['فقط تراکنش‌های تسویه شده قابل تخصیص هستند'],
            ]);
        }

        if ($amount <= 0) {
            throw ValidationException::withMessages([
                'amount' => ['مبلغ تخصیص باید بزرگتر از صفر باشد'],
            ]);
        }

        $this->validateAllocation($transaction, $amount);

        return TransactionAllocation::create([
            'transaction_id' => $transaction->id,
            'debtor_user_id' => $debtor->id,
            'creditor_user_id' => $creditor->id,
            'amount' => $amount,
            'notes' => $notes,
        ]);
    }

    /**
     * Validate allocation does not exceed transaction amount.
     */
    public function validateAllocation(Transaction $transaction, float $newAmount): void
    {
        $existingAllocated = $transaction->allocations()->sum('amount');

        $remaining = $transaction->amount - $existingAllocated;

        if ($newAmount > $remaining) {
            throw ValidationException::withMessages([
                'amount' => ['مبلغ تخصیص از مبلغ تراکنش بیشتر است'],
            ]);
        }
    }

    /**
     * Get remaining allocatable amount for a transaction.
     */
    public function getRemainingAmount(Transaction $transaction): float
    {
        $allocated = $transaction->allocations()->sum('amount');

        return max(0, $transaction->amount - $allocated);
    }
}
