<?php

namespace App\Services;

use App\Models\AccountLedger;

class LedgerService
{
    public function trxNo(string $prefix = 'TRX'): string
    {
        return $prefix.'-'.now()->format('ymdHis').'-'.random_int(100,999);
    }

    public function upsertAccountLedgerForReference(
        int $userId,
        int $accountId,
        string $type,
        string $trxNo,
        string $referenceType,
        int $referenceId,
        float $debit,
        float $credit,
        ?string $description = null,
        $postedAt = null
    ): AccountLedger {
        return AccountLedger::updateOrCreate(
            [
                'user_id'         => $userId,
                'reference_type'  => $referenceType,
                'reference_id'    => $referenceId,
            ],
            [
                'user_account_id' => $accountId,
                'type'            => $type,         // ✅ REQUIRED
                'trx_no'          => $trxNo,
                'debit'           => $debit,
                'credit'          => $credit,
                'description'     => $description,
                'posted_at'       => $postedAt ?? now(),
            ]
        );
    }

    public function deleteAccountLedgerByReference(int $userId, string $referenceType, int $referenceId): void
    {
        AccountLedger::where('user_id', $userId)
            ->where('reference_type', $referenceType)
            ->where('reference_id', $referenceId)
            ->delete();
    }
}