<?php

declare(strict_types=1);

namespace App\Console\Commands;

use App\Models\Invoice;
use App\Notifications\SimpleDatabaseNotification;
use App\Services\InvoiceService;
use Illuminate\Console\Command;

class ProcessInvoiceLateFees extends Command
{
    protected $signature = 'finance:process-late-fees';

    protected $description = 'محاسبه جریمه دیرکرد فاکتورهای پرداخت‌نشده و ارسال اعلان';

    public function handle(InvoiceService $invoices): int
    {
        $query = Invoice::query()
            ->where('type', Invoice::TYPE_EXPENSE)
            ->whereIn('status', [Invoice::STATUS_UNPAID, Invoice::STATUS_APPROVED])
            ->whereNotNull('due_at');

        $count = 0;

        $query->chunkById(100, function ($chunk) use ($invoices, &$count): void {
            foreach ($chunk as $invoice) {
                $before = (int) $invoice->late_fee_amount;
                $invoice = $invoices->refreshLateFee($invoice);
                $after = (int) $invoice->late_fee_amount;

                if ($after > 0 && $after !== $before && $invoice->user) {
                    $invoice->user->notify(new SimpleDatabaseNotification(
                        'جریمه دیرکرد فاکتور',
                        'فاکتور «' . ($invoice->title ?: $invoice->number) . '» پرداخت نشده و جریمه دیرکرد اعمال شد: '
                            . number_format($after) . ' تومان',
                        [
                            'type' => 'invoice_late_fee',
                            'invoice_id' => $invoice->id,
                            'late_fee_amount' => $after,
                        ]
                    ));
                    $count++;
                }
            }
        });

        $this->info("Processed late fees / notifications: {$count}");

        return self::SUCCESS;
    }
}
