<?php

namespace App\Console\Commands;

use App\Domain\Financial\Enums\InvoiceStatus;
use App\Domain\Financial\Events\InvoiceOverdue;
use App\Domain\Financial\Models\Invoice;
use Illuminate\Console\Command;

class MarkOverdueInvoices extends Command
{
    protected $signature = 'invoices:mark-overdue';
    protected $description = 'Transition sent invoices to overdue when due_date has passed';

    public function handle(): int
    {
        $count = 0;

        Invoice::where('status', InvoiceStatus::Sent)
            ->whereNotNull('due_date')
            ->where('due_date', '<', now()->toDateString())
            ->where('due_amount', '>', 0)
            ->chunkById(100, function ($invoices) use (&$count) {
                foreach ($invoices as $invoice) {
                    $invoice->update(['status' => InvoiceStatus::Overdue]);
                    InvoiceOverdue::dispatch($invoice);
                    $count++;
                }
            });

        $this->info("Marked {$count} invoice(s) as overdue.");

        return self::SUCCESS;
    }
}
