<?php

namespace App\Console\Commands;

use App\Models\Lookups\PaymentMethod;
use App\Models\Lookups\Status;
use App\Models\Sales\Transaction;
use Illuminate\Console\Command;

class MarkChequesAsDue extends Command
{
    protected $signature = 'cheques:mark-due';

    protected $description = 'Transition PENDING cheques past their maturity date to DUE status';

    public function handle(): int
    {
        $dueStatusId = Status::idOf(Status::CTX_TRANSACTION, Status::DUE);
        $pendingStatusId = Status::idOf(Status::CTX_TRANSACTION, Status::PENDING);

        if (! $dueStatusId || ! $pendingStatusId) {
            $this->error('Required transaction statuses not found. Run LookupSeeder first.');

            return self::FAILURE;
        }

        $chequeMethodIds = PaymentMethod::query()
            ->withoutGlobalScopes()
            ->where('code', PaymentMethod::CHEQUE)
            ->pluck('id');

        $count = Transaction::withoutGlobalScopes()
            ->where('status_id', $pendingStatusId)
            ->whereNotNull('cheque_date')
            ->whereDate('cheque_date', '<=', now()->toDateString())
            ->whereIn('payment_method_id', $chequeMethodIds)
            ->update(['status_id' => $dueStatusId]);

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

        return self::SUCCESS;
    }
}
