<?php

namespace App\Handlers;

use JsonException;
use Openguru\OpenCartFramework\Exceptions\EntityNotFoundException;
use Symfony\Component\HttpFoundation\JsonResponse;
use Openguru\OpenCartFramework\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Openguru\OpenCartFramework\QueryBuilder\Builder;

class FormsHandler
{
    private Builder $builder;

    public function __construct(Builder $builder)
    {
        $this->builder = $builder;
    }

    /**
     * @throws EntityNotFoundException
     * @throws JsonException
     */
    public function getForm(Request $request): JsonResponse
    {
        $alias = $request->json('alias');
        if (! $alias) {
            return new JsonResponse([
                'error' => 'Form alias is required',
            ], Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        $form = $this->builder->newQuery()
            ->from('telecart_forms')
            ->where('alias', '=', $alias)
            ->firstOrNull();

        if (! $form) {
            throw new EntityNotFoundException("Form with alias `{$alias}` not found");
        }

        $schema = json_decode($form['schema'], true, 512, JSON_THROW_ON_ERROR);

        return new JsonResponse([
            'data' => [
                'schema' => $schema,
            ],
        ]);
    }
}
