<?php

namespace App\Handlers;

use App\Exceptions\OrderValidationFailedException;
use App\Services\OrderCreateService;
use Openguru\OpenCartFramework\Http\JsonResponse;
use Openguru\OpenCartFramework\Http\Request;
use Openguru\OpenCartFramework\Http\Response;

class OrderHandler
{
    private OrderCreateService $orderCreateService;

    public function __construct(OrderCreateService $orderCreateService)
    {
        $this->orderCreateService = $orderCreateService;
    }

    public function store(Request $request): JsonResponse
    {
        try {
            $order = $this->orderCreateService->create($request->json(), [
                'ip' => $request->getClientIp(),
                'user_agent' => $request->getUserAgent(),
            ]);

            return new JsonResponse([
                'data' => $order,
            ], Response::HTTP_CREATED);
        } catch (OrderValidationFailedException $exception) {
            return new JsonResponse([
                'data' => $exception->getErrorBag()->firstOfAll(),
            ], Response::HTTP_UNPROCESSABLE_ENTITY);
        }
    }
}
