<?php

namespace App\Services\CreditScore;

use App\Models\Customer;
use App\Models\Loan;
use App\Services\BranchContext;
use App\Services\CustomerRiskService;
use Illuminate\Support\Facades\DB;
use Throwable;

class CreditScoreRefreshCoordinator
{
    public function __construct(
        private readonly BranchContext $branchContext,
        private readonly CustomerRiskService $risk,
    ) {
    }

    public function afterCommitForLoan(Loan $loan, string $trigger): void
    {
        $this->afterCommitIds((int) $loan->customer_id, (int) $loan->branch_id, $trigger);
    }

    public function afterCommitForCustomer(Customer $customer, string $trigger): void
    {
        $this->afterCommitIds((int) $customer->getKey(), (int) $customer->branch_id, $trigger);
    }

    public function afterCommitIds(int $customerId, int $branchId, string $trigger): void
    {
        $callback = function () use ($customerId, $branchId, $trigger): void {
            try {
                $this->branchContext->forBranch($branchId, function () use ($customerId, $trigger): void {
                    $customer = Customer::query()->find($customerId);
                    if ($customer) {
                        $this->risk->refreshWithHistory($customer, $trigger);
                    }
                });
            } catch (Throwable $exception) {
                report($exception);
            }
        };

        if (DB::transactionLevel() > 0) {
            DB::afterCommit($callback);
            return;
        }

        $callback();
    }
}
