<?php

declare(strict_types=1);

namespace App\Scolarite\Infrastructure\Api\Resource;

use ApiPlatform\Metadata\ApiProperty;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Delete;
use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\Post;
use ApiPlatform\Metadata\Put;
use App\Scolarite\Domain\Model\Grade\AppreciationTemplate;
use App\Scolarite\Infrastructure\Api\Processor\CreateAppreciationTemplateProcessor;
use App\Scolarite\Infrastructure\Api\Processor\DeleteAppreciationTemplateProcessor;
use App\Scolarite\Infrastructure\Api\Processor\UpdateAppreciationTemplateProcessor;
use App\Scolarite\Infrastructure\Api\Provider\AppreciationTemplateCollectionProvider;
use DateTimeImmutable;
use Symfony\Component\Validator\Constraints as Assert;

#[ApiResource(
    shortName: 'AppreciationTemplate',
    operations: [
        new GetCollection(
            uriTemplate: '/me/appreciation-templates',
            provider: AppreciationTemplateCollectionProvider::class,
            name: 'get_appreciation_templates',
        ),
        new Post(
            uriTemplate: '/me/appreciation-templates',
            read: false,
            processor: CreateAppreciationTemplateProcessor::class,
            validationContext: ['groups' => ['Default', 'create']],
            name: 'create_appreciation_template',
        ),
        new Put(
            uriTemplate: '/me/appreciation-templates/{id}',
            read: false,
            processor: UpdateAppreciationTemplateProcessor::class,
            validationContext: ['groups' => ['Default', 'update']],
            name: 'update_appreciation_template',
        ),
        new Delete(
            uriTemplate: '/me/appreciation-templates/{id}',
            read: false,
            processor: DeleteAppreciationTemplateProcessor::class,
            name: 'delete_appreciation_template',
        ),
    ],
)]
final class AppreciationTemplateResource
{
    #[ApiProperty(identifier: true)]
    public ?string $id = null;

    #[Assert\NotBlank(groups: ['create', 'update'])]
    #[Assert\Length(max: 100, groups: ['create', 'update'])]
    public ?string $title = null;

    #[Assert\NotBlank(groups: ['create', 'update'])]
    #[Assert\Length(max: 500, groups: ['create', 'update'])]
    public ?string $content = null;

    public ?string $category = null;

    public ?int $usageCount = null;

    public ?DateTimeImmutable $createdAt = null;

    public ?DateTimeImmutable $updatedAt = null;

    public static function fromDomain(AppreciationTemplate $template): self
    {
        $resource = new self();
        $resource->id = (string) $template->id;
        $resource->title = $template->title;
        $resource->content = $template->content;
        $resource->category = $template->category?->value;
        $resource->usageCount = $template->usageCount;
        $resource->createdAt = $template->createdAt;
        $resource->updatedAt = $template->updatedAt;

        return $resource;
    }
}
