<?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\ClientRibProcessor;
use App\Module\Commercial\Infrastructure\Doctrine\DoctrineClientRibRepository;
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;

/**
 * Coordonnees bancaires d'un client (1:n) — onglet Comptabilite. Au moins un
 * RIB est obligatoire si le type de reglement du client est LCR (RG-1.13,
 * verifie au ClientRibProcessor : refus du DELETE du dernier RIB sous LCR).
 *
 * Audit (#[Auditable]) : TOUS les champs sont audites, y compris `iban` et
 * `bic` — AUCUN #[AuditIgnore] (decision Matthieu en revue MR 29/05/2026 :
 * l'audit etant admin-only, la tracabilite RIB est necessaire pour le suivi
 * comptable et la conformite, cf. spec § 2.5 / § 6.1).
 *
 * Validation IBAN/BIC : Assert\Iban + Assert\Bic standard Symfony au M1
 * (HP-M2-14 : pas de controle externe banque reelle), avec controle croise pays
 * BIC/IBAN (ibanPropertyPath). Timestampable/Blamable standard.
 *
 * Sous-ressource API (ERP-57, spec § 4.5) — gating comptable renforce :
 *  - POST /api/clients/{clientId}/ribs : creation rattachee au client parent
 *    (Link toProperty 'client'), security commercial.clients.accounting.manage.
 *  - PATCH / DELETE /api/client_ribs/{id} : security commercial.clients.accounting.manage.
 *  - GET /api/client_ribs/{id} : lecture unitaire, security
 *    commercial.clients.accounting.view (donnees bancaires sensibles). Pas de
 *    GET collection autonome.
 * Tout passe par le ClientRibProcessor (RG-1.13 sur DELETE).
 */
#[ApiResource(
    operations: [
        new Get(
            security: "is_granted('commercial.clients.accounting.view')",
            normalizationContext: ['groups' => ['client_rib:read']],
        ),
        new Post(
            uriTemplate: '/clients/{clientId}/ribs',
            uriVariables: [
                'clientId' => new Link(fromClass: Client::class, toProperty: 'client'),
            ],
            // read:false : pas de stade lecture du parent. Le Link toProperty
            // resoudrait l'enfant (SELECT ClientRib ... WHERE client = :id) et
            // casse en NonUniqueResult des >= 2 enfants. Le parent est rattache
            // manuellement par ClientRibProcessor::linkParent (404 si absent).
            read: false,
            security: "is_granted('commercial.clients.accounting.manage')",
            normalizationContext: ['groups' => ['client_rib:read']],
            denormalizationContext: ['groups' => ['client_rib:write']],
            processor: ClientRibProcessor::class,
        ),
        new Patch(
            security: "is_granted('commercial.clients.accounting.manage')",
            normalizationContext: ['groups' => ['client_rib:read']],
            denormalizationContext: ['groups' => ['client_rib:write']],
            processor: ClientRibProcessor::class,
        ),
        new Delete(
            security: "is_granted('commercial.clients.accounting.manage')",
            processor: ClientRibProcessor::class,
        ),
    ],
)]
#[ORM\Entity(repositoryClass: DoctrineClientRibRepository::class)]
#[ORM\Table(name: 'client_rib')]
#[ORM\Index(name: 'idx_client_rib_client', columns: ['client_id'])]
#[Auditable]
class ClientRib implements TimestampableInterface, BlamableInterface
{
    use TimestampableBlamableTrait;

    // Double groupe de lecture :
    //  - `client_rib:read` : sous-ressource autonome GET /api/client_ribs/{id}
    //    (deja securisee par commercial.clients.accounting.view).
    //  - `client:read:accounting` : embed des RIB sous le detail Client, ajoute
    //    DYNAMIQUEMENT par ClientReadGroupContextBuilder uniquement si l'user a
    //    accounting.view. Ce double marquage gate les RIB embarques au meme titre
    //    que les scalaires comptables (RG : la Commerciale ne voit aucun RIB).
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column]
    #[Groups(['client_rib:read', 'client:read:accounting'])]
    private ?int $id = null;

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

    #[ORM\Column(length: 120)]
    #[Assert\NotBlank(message: 'Le libellé du RIB est obligatoire.', normalizer: 'trim')]
    #[Assert\Length(max: 120, maxMessage: 'Le libellé ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
    #[Groups(['client_rib:read', 'client:read:accounting', 'client_rib:write'])]
    private ?string $label = null;

    // Bic/Iban bornent deja le format (et donc la longueur) : pas de Length
    // redondant calee sur la colonne (whitelist du garde-fou ERP-107).
    // ibanPropertyPath : controle croise — le pays du BIC (positions 5-6) doit
    // correspondre au pays de l'IBAN (positions 1-2). Violation portee sur `bic`.
    #[ORM\Column(length: 20)]
    #[Assert\NotBlank(message: 'Le BIC est obligatoire.', normalizer: 'trim')]
    #[Assert\Bic(
        message: 'Le BIC n\'est pas valide.',
        ibanPropertyPath: 'iban',
        ibanMessage: 'Le BIC ne correspond pas au pays de l\'IBAN.',
    )]
    #[Groups(['client_rib:read', 'client:read:accounting', 'client_rib:write'])]
    private ?string $bic = null;

    #[ORM\Column(length: 34)]
    #[Assert\NotBlank(message: 'L\'IBAN est obligatoire.', normalizer: 'trim')]
    #[Assert\Iban(message: 'L\'IBAN n\'est pas valide.')]
    #[Groups(['client_rib:read', 'client:read:accounting', 'client_rib:write'])]
    private ?string $iban = null;

    #[ORM\Column(options: ['default' => 0])]
    #[Groups(['client_rib:read', 'client:read:accounting', 'client_rib: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 getLabel(): ?string
    {
        return $this->label;
    }

    public function setLabel(string $label): static
    {
        $this->label = $label;

        return $this;
    }

    public function getBic(): ?string
    {
        return $this->bic;
    }

    public function setBic(string $bic): static
    {
        $this->bic = $bic;

        return $this;
    }

    public function getIban(): ?string
    {
        return $this->iban;
    }

    public function setIban(string $iban): static
    {
        $this->iban = $iban;

        return $this;
    }

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

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

        return $this;
    }
}
