<?php

declare(strict_types=1);

namespace App\Module\Commercial\Domain\Entity;

use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Delete;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\Link;
use ApiPlatform\Metadata\Patch;
use ApiPlatform\Metadata\Post;
use App\Module\Commercial\Infrastructure\ApiPlatform\State\Processor\ClientContactProcessor;
use App\Module\Commercial\Infrastructure\Doctrine\DoctrineClientContactRepository;
use App\Shared\Domain\Attribute\Auditable;
use App\Shared\Domain\Contract\BlamableInterface;
use App\Shared\Domain\Contract\TimestampableInterface;
use App\Shared\Domain\Trait\TimestampableBlamableTrait;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Attribute\Groups;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Contact d'un client (1:n) — onglet Contact. Au moins firstName OU lastName
 * doit etre renseigne (RG-1.05) : la contrainte est portee par un CHECK BDD
 * (chk_client_contact_name) et validee dans le ClientContactProcessor ;
 * l'entite reste permissive (les deux champs sont nullable).
 *
 * Audite (#[Auditable]) + Timestampable/Blamable (pattern Shared standard).
 *
 * Sous-ressource API (ERP-57, spec § 4.5) :
 *  - POST /api/clients/{clientId}/contacts : creation rattachee au client parent
 *    (Link toProperty 'client'), security commercial.clients.manage.
 *  - PATCH / DELETE /api/client_contacts/{id} : security commercial.clients.manage.
 *    Le DELETE est physique (sous-collection, pas le client) ; le processor
 *    refuse la suppression du dernier contact (RG-1.14, 409).
 *  - GET /api/client_contacts/{id} : lecture unitaire (security view) — la
 *    lecture courante reste via le parent (client embarque ses contacts). Pas de
 *    GET collection autonome : non concernee par la pagination ERP-72.
 * Tout passe par le ClientContactProcessor (normalisation RG-1.19/1.20/1.21).
 */
#[ApiResource(
    operations: [
        new Get(
            security: "is_granted('commercial.clients.view')",
            normalizationContext: ['groups' => ['client_contact:read']],
        ),
        new Post(
            uriTemplate: '/clients/{clientId}/contacts',
            uriVariables: [
                'clientId' => new Link(fromClass: Client::class, toProperty: 'client'),
            ],
            // read:false : pas de stade lecture du parent. Le Link toProperty
            // resoudrait l'enfant (SELECT ClientContact ... WHERE client = :id) et
            // casse en NonUniqueResult des >= 2 enfants. Le parent est rattache
            // manuellement par ClientContactProcessor::linkParent (404 si absent).
            read: false,
            security: "is_granted('commercial.clients.manage')",
            normalizationContext: ['groups' => ['client_contact:read']],
            denormalizationContext: ['groups' => ['client_contact:write']],
            processor: ClientContactProcessor::class,
        ),
        new Patch(
            security: "is_granted('commercial.clients.manage')",
            normalizationContext: ['groups' => ['client_contact:read']],
            denormalizationContext: ['groups' => ['client_contact:write']],
            processor: ClientContactProcessor::class,
        ),
        new Delete(
            security: "is_granted('commercial.clients.manage')",
            processor: ClientContactProcessor::class,
        ),
    ],
)]
#[ORM\Entity(repositoryClass: DoctrineClientContactRepository::class)]
#[ORM\Table(name: 'client_contact')]
#[ORM\Index(name: 'idx_client_contact_client', columns: ['client_id'])]
#[Auditable]
class ClientContact implements TimestampableInterface, BlamableInterface
{
    use TimestampableBlamableTrait;

    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column]
    #[Groups(['client_contact:read'])]
    private ?int $id = null;

    #[ORM\ManyToOne(targetEntity: Client::class, inversedBy: 'contacts')]
    #[ORM\JoinColumn(name: 'client_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')]
    private ?Client $client = null;

    // RG-1.05 : firstName OU lastName obligatoire (CHECK BDD + Processor). Les
    // deux restent nullable au niveau ORM.
    #[ORM\Column(length: 120, nullable: true)]
    #[Assert\Length(max: 120, maxMessage: 'Le prénom ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
    #[Groups(['client_contact:read', 'client_contact:write'])]
    private ?string $firstName = null;

    #[ORM\Column(length: 120, nullable: true)]
    #[Assert\Length(max: 120, maxMessage: 'Le nom ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
    #[Groups(['client_contact:read', 'client_contact:write'])]
    private ?string $lastName = null;

    #[ORM\Column(length: 120, nullable: true)]
    #[Assert\Length(max: 120, maxMessage: 'La fonction ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
    #[Groups(['client_contact:read', 'client_contact:write'])]
    private ?string $jobTitle = null;

    // RG : pas de validation de format telephone (saisie libre), mais une
    // Assert\Length calee sur la colonne VARCHAR(20) evite l'erreur Postgres
    // (500 non rattachee au champ) au profit d'une 422 propre (ERP-107).
    #[ORM\Column(length: 20, nullable: true)]
    #[Assert\Length(max: 20, maxMessage: 'Le téléphone ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
    #[Groups(['client_contact:read', 'client_contact:write'])]
    private ?string $phonePrimary = null;

    #[ORM\Column(length: 20, nullable: true)]
    #[Assert\Length(max: 20, maxMessage: 'Le téléphone secondaire ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
    #[Groups(['client_contact:read', 'client_contact:write'])]
    private ?string $phoneSecondary = null;

    #[ORM\Column(length: 180, nullable: true)]
    #[Assert\Email(message: 'L\'adresse email n\'est pas valide.')]
    #[Assert\Length(max: 180, maxMessage: 'L\'email ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
    #[Groups(['client_contact:read', 'client_contact:write'])]
    private ?string $email = null;

    #[ORM\Column(options: ['default' => 0])]
    #[Groups(['client_contact:read', 'client_contact:write'])]
    private int $position = 0;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getClient(): ?Client
    {
        return $this->client;
    }

    public function setClient(?Client $client): static
    {
        $this->client = $client;

        return $this;
    }

    public function getFirstName(): ?string
    {
        return $this->firstName;
    }

    public function setFirstName(?string $firstName): static
    {
        $this->firstName = $firstName;

        return $this;
    }

    public function getLastName(): ?string
    {
        return $this->lastName;
    }

    public function setLastName(?string $lastName): static
    {
        $this->lastName = $lastName;

        return $this;
    }

    public function getJobTitle(): ?string
    {
        return $this->jobTitle;
    }

    public function setJobTitle(?string $jobTitle): static
    {
        $this->jobTitle = $jobTitle;

        return $this;
    }

    public function getPhonePrimary(): ?string
    {
        return $this->phonePrimary;
    }

    public function setPhonePrimary(?string $phonePrimary): static
    {
        $this->phonePrimary = $phonePrimary;

        return $this;
    }

    public function getPhoneSecondary(): ?string
    {
        return $this->phoneSecondary;
    }

    public function setPhoneSecondary(?string $phoneSecondary): static
    {
        $this->phoneSecondary = $phoneSecondary;

        return $this;
    }

    public function getEmail(): ?string
    {
        return $this->email;
    }

    public function setEmail(?string $email): static
    {
        $this->email = $email;

        return $this;
    }

    public function getPosition(): int
    {
        return $this->position;
    }

    public function setPosition(int $position): static
    {
        $this->position = $position;

        return $this;
    }
}
