<?php

declare(strict_types=1);

namespace App\Scolarite\Infrastructure\Api\Provider;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Administration\Infrastructure\Security\SecurityUser;
use App\Scolarite\Infrastructure\Api\Resource\CompetencyResource;
use App\Shared\Infrastructure\Tenant\TenantContext;

use function array_map;

use Doctrine\DBAL\Connection;
use Override;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;

/**
 * @implements ProviderInterface<CompetencyResource>
 */
final readonly class CompetencyCollectionProvider implements ProviderInterface
{
    public function __construct(
        private Connection $connection,
        private TenantContext $tenantContext,
        private Security $security,
    ) {
    }

    /** @return array<CompetencyResource> */
    #[Override]
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): array
    {
        if (!$this->tenantContext->hasTenant()) {
            throw new UnauthorizedHttpException('Bearer', 'Tenant non défini.');
        }

        $user = $this->security->getUser();

        if (!$user instanceof SecurityUser) {
            throw new UnauthorizedHttpException('Bearer', 'Authentification requise.');
        }

        $tenantId = (string) $this->tenantContext->getCurrentTenantId();

        $rows = $this->connection->fetchAllAssociative(
            'SELECT c.id, c.framework_id, c.code, c.name, c.description, c.parent_id, c.sort_order,
                    cf.name AS framework_name
             FROM competencies c
             JOIN competency_frameworks cf ON cf.id = c.framework_id
             WHERE cf.tenant_id = :tenant_id
             AND cf.is_default = true
             ORDER BY c.sort_order ASC',
            ['tenant_id' => $tenantId],
        );

        return array_map(static function (array $row): CompetencyResource {
            $resource = new CompetencyResource();
            /** @var string $id */
            $id = $row['id'];
            $resource->id = $id;
            /** @var string $frameworkId */
            $frameworkId = $row['framework_id'];
            $resource->frameworkId = $frameworkId;
            /** @var string $frameworkName */
            $frameworkName = $row['framework_name'];
            $resource->frameworkName = $frameworkName;
            /** @var string $code */
            $code = $row['code'];
            $resource->code = $code;
            /** @var string $name */
            $name = $row['name'];
            $resource->name = $name;
            /** @var string|null $description */
            $description = $row['description'];
            $resource->description = $description;
            /** @var string|null $parentId */
            $parentId = $row['parent_id'];
            $resource->parentId = $parentId;
            /** @var string|int $sortOrder */
            $sortOrder = $row['sort_order'];
            $resource->sortOrder = (int) $sortOrder;

            return $resource;
        }, $rows);
    }
}
