<?php

declare(strict_types=1);

namespace App\Controller;

use App\Repository\ModelTypeRepository;
use App\Service\ModelTypeCategoryConversionService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

final class ModelTypeConversionController extends AbstractController
{
    public function __construct(
        private readonly ModelTypeRepository $modelTypes,
        private readonly ModelTypeCategoryConversionService $conversionService,
    ) {}

    #[Route('/api/model_types/{id}/conversion-check', name: 'api_model_type_conversion_check', methods: ['GET'])]
    public function check(string $id): JsonResponse
    {
        $this->denyAccessUnlessGranted('ROLE_VIEWER');

        $modelType = $this->modelTypes->find($id);

        if (!$modelType) {
            return new JsonResponse(
                ['message' => 'Catégorie introuvable.'],
                Response::HTTP_NOT_FOUND,
            );
        }

        return new JsonResponse($this->conversionService->checkConversion($id));
    }

    #[Route('/api/model_types/{id}/convert', name: 'api_model_type_convert', methods: ['POST'])]
    public function convert(string $id): JsonResponse
    {
        $this->denyAccessUnlessGranted('ROLE_GESTIONNAIRE');

        $modelType = $this->modelTypes->find($id);

        if (!$modelType) {
            return new JsonResponse(
                ['message' => 'Catégorie introuvable.'],
                Response::HTTP_NOT_FOUND,
            );
        }

        $result = $this->conversionService->convert($id);

        if (!$result['success']) {
            return new JsonResponse($result, Response::HTTP_CONFLICT);
        }

        return new JsonResponse($result);
    }
}
