<?php

namespace App\Services\Authorization;

use App\Models\Loan;
use App\Models\LoanRestructuring;
use App\Models\RemotePaymentSubmission;
use App\Models\User;
use Illuminate\Validation\ValidationException;

class FinancialMakerCheckerService
{
    public function assertLoanDisbursementSeparated(Loan $loan, User $user): void
    {
        $loan->loadMissing('branch.business');

        if ($this->enabled($loan->branch?->business?->maker_checker_enabled)
            && $loan->approved_by
            && (int) $loan->approved_by === (int) $user->id) {
            throw ValidationException::withMessages([
                'loan' => 'Maker-checker is enabled. The employee who approved this loan cannot also disburse it.',
            ]);
        }
    }

    public function assertTopUpExecutionSeparated(Loan $replacementLoan, User $user): void
    {
        $replacementLoan->loadMissing('branch.business');

        if ($this->enabled($replacementLoan->branch?->business?->maker_checker_enabled)
            && $replacementLoan->approved_by
            && (int) $replacementLoan->approved_by === (int) $user->id) {
            throw ValidationException::withMessages([
                'loan' => 'Maker-checker is enabled. The employee who approved this replacement loan cannot also execute its top-up disbursement.',
            ]);
        }
    }

    public function assertRestructuringDecisionSeparated(LoanRestructuring $restructuring, User $user): void
    {
        $restructuring->loadMissing('branch.business');

        if ($this->enabled($restructuring->branch?->business?->maker_checker_enabled)
            && (int) $restructuring->requested_by === (int) $user->id) {
            throw ValidationException::withMessages([
                'restructuring' => 'Maker-checker is enabled. The employee who requested this restructuring cannot decide it.',
            ]);
        }
    }

    public function assertRemotePaymentVerificationSeparated(RemotePaymentSubmission $submission, User $user): void
    {
        $submission->loadMissing('branch.business');

        if ($submission->submitted_by_type === 'staff'
            && $this->enabled($submission->branch?->business?->maker_checker_enabled)
            && $submission->submitted_by_user_id
            && (int) $submission->submitted_by_user_id === (int) $user->id) {
            throw ValidationException::withMessages([
                'status' => 'Maker-checker is enabled. The employee who submitted this remote payment cannot verify it.',
            ]);
        }
    }

    private function enabled(mixed $value): bool
    {
        return (bool) $value;
    }
}
