<?php

namespace App\Console\Commands;

use App\Models\Order;
use App\Models\Shipment;
use Illuminate\Console\Command;

class AutoDeliverManualShipments extends Command
{
    protected $signature = 'orders:auto-deliver-manual-shipments';

    protected $description = 'Set order and shipment status to Delivered for manual carrier shipments older than 5 days';

    public function handle(): int
    {
        $cutoff = now()->subDays(5);
        $updated = 0;

        Order::query()
            ->where('status', Order::STATUS_SHIPPED)
            ->whereHas('shipments', function ($q) use ($cutoff) {
                $q->whereHas('carrier', function ($cq) {
                    $cq->where('process_type', 'manual');
                })->where('created_at', '<=', $cutoff);
            })
            ->with(['shipments' => function ($q) {
                $q->whereHas('carrier', fn ($cq) => $cq->where('process_type', 'manual'));
            }])
            ->chunkById(100, function ($orders) use (&$updated) {
                foreach ($orders as $order) {
                    $order->update(['status' => Order::STATUS_DELIVERED]);
                    $order->shipments()->whereHas('carrier', fn ($q) => $q->where('process_type', 'manual'))
                        ->update(['status' => Shipment::STATUS_DELIVERED]);
                    $updated++;
                }
            });

        if ($updated > 0) {
            $this->info("Auto-delivered {$updated} order(s) with manual shipments older than 5 days.");
        }

        return Command::SUCCESS;
    }
}
