<?php

namespace App\Services\Concerns;

use App\Enums\CashTransactionType;
use App\Models\CashAccount;
use App\Models\CashTransaction;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;

trait HandlesCashTransactions
{
    private function getCashAccount(): CashAccount
    {
        return CashAccount::firstOrFail();
    }

    private function creditCash(int $amount, string $description, CashTransactionType $type = CashTransactionType::DEPOSIT): CashTransaction
    {
        return DB::transaction(function () use ($amount, $description, $type) {
            $cashAccount = $this->getCashAccount();
            $newBalance = $cashAccount->balance + $amount;

            $cashAccount->update(['balance' => $newBalance]);

            return CashTransaction::create([
                'cash_account_id' => $cashAccount->id,
                'created_by_id' => auth()->id(),
                'amount' => $amount,
                'balance_after' => $newBalance,
                'type' => $type,
                'description' => $description,
            ]);
        });
    }

    private function debitCash(int $amount, string $description, CashTransactionType $type = CashTransactionType::EXPENSE): CashTransaction
    {
        return DB::transaction(function () use ($amount, $description, $type) {
            $cashAccount = $this->getCashAccount();

            if ($cashAccount->balance < $amount) {
                throw ValidationException::withMessages([
                    'amount' => 'Saldo tidak mencukupi.',
                ]);
            }

            $newBalance = $cashAccount->balance - $amount;
            $cashAccount->update(['balance' => $newBalance]);

            return CashTransaction::create([
                'cash_account_id' => $cashAccount->id,
                'created_by_id' => auth()->id(),
                'amount' => $amount,
                'balance_after' => $newBalance,
                'type' => $type,
                'description' => $description,
            ]);
        });
    }
}
