<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Resource;

use ApiPlatform\Metadata\ApiProperty;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\Put;
use App\Administration\Domain\Model\HomeworkRules\HomeworkRule;
use App\Administration\Domain\Model\HomeworkRules\HomeworkRules;
use App\Administration\Infrastructure\Api\Processor\UpdateHomeworkRulesProcessor;
use App\Administration\Infrastructure\Api\Provider\HomeworkRulesProvider;

use function array_map;

use DateTimeImmutable;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * API Resource pour la configuration des règles de devoirs.
 *
 * @see FR81 - Configurer règles de timing des devoirs
 */
#[ApiResource(
    shortName: 'HomeworkRules',
    operations: [
        new Get(
            uriTemplate: '/settings/homework-rules',
            provider: HomeworkRulesProvider::class,
            name: 'get_homework_rules',
        ),
        new Put(
            uriTemplate: '/settings/homework-rules',
            read: false,
            processor: UpdateHomeworkRulesProcessor::class,
            name: 'update_homework_rules',
        ),
    ],
)]
final class HomeworkRulesResource
{
    #[ApiProperty(identifier: true)]
    public ?string $id = null;

    /** @var array<int, array{type: string, params: array<string, mixed>}>|null */
    #[Assert\NotNull(message: 'Les règles sont obligatoires.')]
    public ?array $rules = null;

    #[Assert\NotBlank(message: 'Le mode d\'application est obligatoire.')]
    #[Assert\Choice(choices: ['soft', 'hard', 'disabled'], message: 'Mode invalide.')]
    public ?string $enforcementMode = null;

    public ?bool $enabled = null;

    public ?DateTimeImmutable $createdAt = null;
    public ?DateTimeImmutable $updatedAt = null;

    public static function fromDomain(HomeworkRules $homeworkRules): self
    {
        $resource = new self();
        $resource->id = (string) $homeworkRules->id;
        $resource->rules = array_map(
            static fn (HomeworkRule $rule): array => $rule->toArray(),
            $homeworkRules->rules,
        );
        $resource->enforcementMode = $homeworkRules->enforcementMode->value;
        $resource->enabled = $homeworkRules->enabled;
        $resource->createdAt = $homeworkRules->createdAt;
        $resource->updatedAt = $homeworkRules->updatedAt;

        return $resource;
    }
}
