<?php
namespace App\Console\Commands;
use App\Enums\JournalStatus;
use App\Models\JournalEntry;
use App\Support\Decimal;
use Illuminate\Console\Command;
final class AccountingIntegrityCheck extends Command
{
    protected $signature='accounting:integrity-check'; protected $description='Verify every posted journal is balanced and has at least two lines.';
    public function handle(): int
    {
        $failures=0; JournalEntry::query()->where('status',JournalStatus::POSTED->value)->with('lines')->chunkById(200,function($journals) use(&$failures): void { foreach($journals as $journal){ $debit=Decimal::scale('0');$credit=Decimal::scale('0');foreach($journal->lines as $line){$debit=Decimal::add($debit,$line->debit);$credit=Decimal::add($credit,$line->credit);} if($journal->lines->count()<2||!Decimal::equals($debit,$credit)||!Decimal::equals($debit,$journal->debit_total)||!Decimal::equals($credit,$journal->credit_total)){ $this->error("Journal {$journal->journal_number} failed integrity checks.");$failures++; } } }); if($failures>0){$this->error("{$failures} journal(s) failed.");return self::FAILURE;} $this->info('All posted journals are balanced.');return self::SUCCESS;
    }
}
