<?php

declare(strict_types=1);

namespace Drupal\conductor\Controller;

use Drupal\conductor\ConductorHttpApiClient;
use Drupal\conductor\Exception\ConductorCredentialsNotFoundException;
use Drupal\conductor\Repository\DraftRepository;
use Drupal\conductor\Repository\DraftRepositoryInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;

/**
 * Controller for returning conductor settings via the API.
 */
final readonly class ConductorSettingsApiController implements ContainerInjectionInterface {

  public function __construct(
    private ConductorHttpApiClient $conductorHttpApiClient,
    private DraftRepositoryInterface $draftRepository,
  ) {}

  public static function create(ContainerInterface $container): self {
    return new self(
      $container->get(ConductorHttpApiClient::class),
      $container->get(DraftRepository::class),
    );
  }

  public function __invoke(): JsonResponse {
    try {
      $accountId = $this->conductorHttpApiClient->getAccountId();
    }
    catch (ConductorCredentialsNotFoundException $e) {
      return new JsonResponse(['error' => $e->getMessage()], Response::HTTP_UNAUTHORIZED);
    }
    catch (\Exception $e) {
      return new JsonResponse(['error' => $e->getMessage()], Response::HTTP_INTERNAL_SERVER_ERROR);
    }

    return new JsonResponse([
      'accountId' => $accountId,
      'maxDrafts' => $this->draftRepository->getMaxDrafts(),
      'usedDrafts' => $this->draftRepository->getUsedDrafts(),
    ]);
  }

}
