<?php

define('APP_PATH', __DIR__ . '/../application/');

require __DIR__ . '/../thinkphp/base.php';

\think\App::initCommon();

use think\Queue;
use app\admin\model\shopro\order\Order;
use app\admin\model\shopro\order\OrderItem;

$mode = $argv[1] ?? '';

if (!in_array($mode, ['confirm', 'comment'], true)) {
    echo "Usage:\n";
    echo "  php runtime/requeue_auto_order_fix.php confirm\n";
    echo "  php runtime/requeue_auto_order_fix.php comment\n";
    exit(1);
}

$confirmOrderIds = [22, 24, 25];
$commentOrderIds = [22, 24, 25, 27];

if ($mode === 'confirm') {
    foreach ($confirmOrderIds as $orderId) {
        $order = Order::paid()->where('id', $orderId)->find();

        if (!$order) {
            echo "[skip confirm] order {$orderId} not found or not paid\n";
            continue;
        }

        $items = OrderItem::where('order_id', $orderId)->select();

        if (!$items || count($items) <= 0) {
            echo "[skip confirm] order {$orderId} has no items\n";
            continue;
        }

        Queue::push(
            '\\addons\\shopro\\job\\OrderAutoOper@autoConfirm',
            [
                'order' => $order->toArray(),
                'items' => collection($items)->toArray(),
            ],
            'shopro'
        );

        echo "[queued confirm] order {$orderId}, items=" . count($items) . "\n";
    }

    exit(0);
}

if ($mode === 'comment') {
    foreach ($commentOrderIds as $orderId) {
        $order = Order::paid()->where('id', $orderId)->find();

        if (!$order) {
            echo "[skip comment] order {$orderId} not found or not paid\n";
            continue;
        }

        $items = OrderItem::where('order_id', $orderId)->select();

        if (!$items || count($items) <= 0) {
            echo "[skip comment] order {$orderId} has no items\n";
            continue;
        }

        foreach ($items as $item) {
            Queue::push(
                '\\addons\\shopro\\job\\OrderAutoOper@autoComment',
                [
                    'order' => $order->toArray(),
                    'item' => $item->toArray(),
                ],
                'shopro'
            );

            echo "[queued comment] order {$orderId}, item {$item->id}\n";
        }
    }

    exit(0);
}