<?php

namespace App\Domain\Setting\Infrastructure\ApiPlatform\State\Provider;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Domain\Setting\Domain\Contract\Repository\ContentSourceRepositoryInterface;
use App\Domain\Setting\Domain\Exception\ContentSourceNotFoundException;
use App\Domain\Setting\Infrastructure\ApiPlatform\Resource\DeleteContentSourceResource;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

readonly class DeleteContentSourceStateProvider implements ProviderInterface
{
    public function __construct(
        private ContentSourceRepositoryInterface $contentSourceRepository
    ) {
    }

    public function provide(Operation $operation, array $uriVariables = [], array $context = []): DeleteContentSourceResource
    {
        if (!isset($uriVariables['id'])) {
            throw new NotFoundHttpException('Content source ID is required');
        }

        $id = (int) $uriVariables['id'];

        try {
            $contentSource = $this->contentSourceRepository->findById($id);

            if (!$contentSource) {
                throw new ContentSourceNotFoundException($id);
            }

            return new DeleteContentSourceResource($id);
        } catch (ContentSourceNotFoundException $e) {
            throw new NotFoundHttpException($e->getMessage());
        }
    }
}
