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


namespace App\ApiResource;

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\Sale;
use App\Enum\PartnerType;
use App\Interface\OwnerInterface;
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\Validator\Constraints\NotBlank;

#[ApiResource(
    shortName: 'Sale',
    operations: [
        new Get(
            security: 'is_granted("ROLE_USER")'
        ),
        new GetCollection(),
        new Post(
            security: 'is_granted("ROLE_USER")',
        ),
        new Patch(
            security: 'is_granted("EDIT", object)',
        ),
//        new Delete(
//            security: 'is_granted("ROLE_ADMIN")',
//        )
    ],
    order: ['createdAt' => 'DESC'],
    security: 'is_granted("ROLE_USER")',
    provider: EntityToDtoStateProvider::class,
    processor: EntityClassDtoStateProcessor::class,
    stateOptions: new Options(entityClass: Sale::class),
)]
#[ApiFilter(SearchFilter::class, properties: ['owner' => 'exact', 'partner' => 'exact'])]
class SaleApi implements OwnerInterface
{
    #[ApiProperty(readable: false, writable: false, identifier: true)]
    public ?int $id = null;

    #[ApiProperty(writable: false)]
    public ?UserApi $owner = null;

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

    #[ApiProperty(writable: true)]
    public ?PartnerApi $partner = null;

    #[ApiProperty(writable: false)]
    public PartnerType $partnerType;

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

    #[ApiProperty(writable: true)]
    public ?ProductApi $product = null;

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

    #[NotBlank]
    public ?int $turnover = null;

    #[NotBlank]
    public ?int $profit = null;

    #[NotBlank]
    public ?int $quantity = null;

    public ?string $comment = null;

    #[ApiProperty(writable: false)]
    public ?\DateTimeImmutable $createdAt = null;

    /**
     * @var $posts array<int, PostingApi>
     */
    #[ApiProperty(writable: false)]
    public array $posts = [];

    public function getOwner(): ?UserApi
    {
        return $this->owner;
    }
}