<?php

namespace App\Services\Accounting;

use App\Enums\DocumentStatus;
use DomainException;
use Illuminate\Database\Eloquent\Model;

final class DocumentApprovalGuard
{
    public function ensureApproved(Model $document): void
    {
        if ($document->status !== DocumentStatus::APPROVED) {
            throw new DomainException('Only approved documents can be posted.');
        }

        if (! config('accounting.maker_checker')) {
            return;
        }

        if (! $document->approved_by) {
            throw new DomainException('An approved-by user is required when maker-checker is enabled.');
        }

        if ($document->created_by && (int) $document->created_by === (int) $document->approved_by) {
            throw new DomainException(
                'Maker-checker is enabled: the creator cannot approve the same document.',
            );
        }
    }
}
