<?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())
            ->chunkById(100, function ($invoices) use (&$count) {
                foreach ($invoices as $invoice) {
                    $invoice->update(['status' => InvoiceStatus::Overdue]);
                    InvoiceOverdue::dispatch($invoice);
                    $count++;
                }
            });

        if ($count > 0) {
            $this->info("Marked {$count} invoices as overdue.");
        }

        return self::SUCCESS;
    }
}
