<?php

namespace App\Handlers;

use App\Exceptions\OrderValidationFailedException;
use App\Services\OrderCreateService;
use App\Support\Utf8Cleaner;
use Symfony\Component\HttpFoundation\JsonResponse;
use Openguru\OpenCartFramework\Http\Request;
use Symfony\Component\HttpFoundation\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' => Utf8Cleaner::clean($order),
            ], Response::HTTP_CREATED);
        } catch (OrderValidationFailedException $exception) {
            return new JsonResponse([
                'data' => Utf8Cleaner::clean($exception->getErrorBag()->firstOfAll()),
            ], Response::HTTP_UNPROCESSABLE_ENTITY);
        }
    }
}
