<?php
/**
 * @author Daniel Knudsen <d.knudsen@spawntree.de>
 * @date 12.12.23
 */


namespace App\ApiResource;


use ApiPlatform\Doctrine\Orm\Filter\OrderFilter;
use ApiPlatform\Doctrine\Orm\Filter\SearchFilter;
use ApiPlatform\Doctrine\Orm\State\Options;
use ApiPlatform\Metadata\ApiFilter;
use ApiPlatform\Metadata\ApiProperty;
use ApiPlatform\Metadata\ApiResource;
use App\Entity\MediaObject;
use App\Entity\Product;
use App\Filter\ProductUnassignedFilter;
use App\State\EntityClassDtoStateProcessor;
use App\State\EntityToDtoStateProvider;
use ApiPlatform\Metadata\Delete;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\Patch;
use ApiPlatform\Metadata\Post;
use Symfony\Component\PropertyInfo\Type;
use Symfony\Component\Validator\Constraints\NotBlank;

#[ApiResource(
    shortName: 'Product',
    operations: [
        new Get(
            security: 'is_granted("ROLE_USER")'
        ),
        new GetCollection(),
        new Post(
            security: 'is_granted("ROLE_ADMIN")',
        ),
        new Patch(
            security: 'is_granted("ROLE_ADMIN")',
        ),
//        new Delete(
//            security: 'is_granted("ROLE_ADMIN")',
//        )
    ],
    order: ['name' => 'ASC'],
    security: 'is_granted("ROLE_USER")',
    provider: EntityToDtoStateProvider::class,
    processor: EntityClassDtoStateProcessor::class,
    stateOptions: new Options(entityClass: Product::class)
)]

#[ApiFilter(SearchFilter::class, properties: ['name' => 'ipartial'])]
#[ApiFilter(ProductUnassignedFilter::class)]
#[ApiFilter(OrderFilter::class, properties: ['name'], arguments: ['orderParameterName' => 'order'])]
class ProductApi
{
    #[ApiProperty(readable: false, writable: false, identifier: true)]
    public ?int $id = null;

    #[NotBlank]
    public string $name;

    public ?string $description = null;

    #[NotBlank]
    public ?bool $blocked = null;

    #[NotBlank]
    public ?float $inventory = null;

    public ?string $baseUnit = null;

    public ?string $buyUnit = null;

    public ?string $sellUnit = null;

    public ?string $trackingCode = null;

    public ?string $productGroup = null;

    public ?string $customsPosition = null;

    public ?string $productBookingGroup = null;

    public ?string $vatProductBookingGroup = null;

    public ?MediaObject $image = null;

    #[ApiProperty(writable: false)]
    public ?string $imageUrl = null;

    /**
     * @var $createdBy ?UserApi
     */
    #[ApiProperty(
        writable: false,
        readableLink: true,
        writableLink: false,
        builtinTypes: [
            new Type(
                'object',
                class: UserApi::class,
            )
        ]
    )]
    public ?UserApi $createdBy = null;

    public ?\DateTimeImmutable $createdAt = null;

}