<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\SyncOrdersRequest;
use App\Services\OrderService;
use Illuminate\Http\JsonResponse;

class SyncOrderController extends Controller
{
    public function store(SyncOrdersRequest $request, OrderService $orderService): JsonResponse
    {
        $user = $request->user();
        $results = [];

        foreach ($request->validated('orders') as $orderPayload) {
            $order = $orderService->createPaidOrder($orderPayload, $user->id, (int) $user->outlet_id);
            $results[] = [
                'client_order_id' => $orderPayload['client_order_id'],
                'server_order_id' => $order->id,
                'receipt_number' => $order->receipt_number,
                'status' => $order->status,
            ];
        }

        return response()->json(['data' => $results]);
    }
}
