<?php

namespace App\Console\Commands;

use App\Models\OrderItem;
use App\Models\Setting;
use App\Services\OrderFulfilmentService;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;

#[Signature('orders:auto-reject-overdue')]
#[Description('Enforce the vendor accept SLA: ask the customer to keep waiting, then auto-cancel + refund unanswered orders.')]
class AutoRejectOverdueItems extends Command
{
    public function handle(OrderFulfilmentService $fulfilment): int
    {
        $reconfirm = (string) (Setting::get('sla_reconfirm_enabled') ?? '1') === '1';
        $grace     = (int) (Setting::get('sla_grace_minutes') ?: 15);
        $accept    = (int) (Setting::get('sla_accept_minutes') ?: 30);

        // Phase 2 (and the only phase when re-confirmation is off): the customer
        // was asked to keep waiting and didn't, so cancel + refund as a timeout.
        $reconfirmQuery = OrderItem::where('status', 'pending')
            ->whereNotNull('reconfirm_prompted_at')
            ->whereNotNull('reconfirm_deadline')
            ->where('reconfirm_deadline', '<', now())
            ->with(['order.user', 'product', 'vendor']);

        $timedOut = 0;
        foreach ($reconfirmQuery->get() as $item) {
            $fulfilment->timeoutItem($item);
            $timedOut++;
            $this->line("  - Timed out item #{$item->id} (order {$item->order?->order_number})");
        }

        // Items past their accept window that haven't been escalated yet.
        $overdue = OrderItem::where('status', 'pending')
            ->whereNull('reconfirm_prompted_at')
            ->whereNotNull('sla_deadline')
            ->where('sla_deadline', '<', now())
            ->with(['order.user', 'product', 'vendor'])
            ->get();

        $prompted = 0;
        foreach ($overdue as $item) {
            if ($reconfirm) {
                // Phase 1: ask the customer to keep waiting; nudge the vendor.
                $fulfilment->promptReconfirmation($item, $grace);
                $prompted++;
                $this->line("  - Prompted customer for item #{$item->id} (order {$item->order?->order_number})");
            } else {
                // Re-confirmation disabled: cancel + refund straight away.
                $fulfilment->timeoutItem($item);
                $timedOut++;
                $this->line("  - Auto-cancelled item #{$item->id} (order {$item->order?->order_number})");
            }
        }

        $this->info("Prompted {$prompted}, timed out {$timedOut}.");

        return self::SUCCESS;
    }
}
