<?php

declare(strict_types=1);

namespace App\Module\Technique\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\Technique\Infrastructure\ApiPlatform\State\Processor\ProviderRibProcessor;
use App\Module\Technique\Infrastructure\ApiPlatform\State\Provider\ProviderSubResourceItemProvider;
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 prestataire (1:n) — onglet Comptabilite. Au moins un
 * RIB est obligatoire si le type de reglement est LCR (RG-3.08, verifie au
 * ProviderRibProcessor : refus du DELETE du dernier RIB sous LCR — ERP-135).
 *
 * Embarque sous `provider.ribs` UNIQUEMENT si l'user a accounting.view : le
 * read-group est `provider:read:accounting`, retire du contexte par le
 * ProviderProvider sinon (gating par omission de cle — evite la fuite IBAN/BIC,
 * piege n°4 du M1). Aucun #[AuditIgnore] sur iban/bic : l'audit etant admin-only,
 * la tracabilite RIB est conservee (decision M1 reportee, § 2.7).
 *
 * Sous-ressource API (ERP-135, spec § 4.5) — gating comptable renforce :
 *  - POST /api/providers/{providerId}/ribs : creation rattachee au prestataire
 *    parent (Link toProperty 'provider'), security technique.providers.accounting.manage.
 *  - PATCH / DELETE /api/provider_ribs/{id} : security technique.providers.accounting.manage.
 *    Le DELETE refuse la suppression du dernier RIB sous LCR (RG-3.08, 409).
 *  - GET /api/provider_ribs/{id} : lecture unitaire, security
 *    technique.providers.accounting.view (donnees bancaires sensibles). Pas de GET
 *    collection autonome.
 * Tout passe par le ProviderRibProcessor (RG-3.08 sur DELETE).
 *
 * Validation IBAN/BIC : Assert\Iban + Assert\Bic standard Symfony (pas de controle
 * banque reelle), avec controle croise pays BIC/IBAN (ibanPropertyPath). Audite
 * (#[Auditable]) + Timestampable / Blamable.
 */
#[ApiResource(
    operations: [
        new Get(
            security: "is_granted('technique.providers.accounting.view')",
            normalizationContext: ['groups' => ['provider:read:accounting']],
            // Cloisonnement par site du prestataire parent (§ 2.13) : 404 hors perimetre.
            provider: ProviderSubResourceItemProvider::class,
        ),
        new Post(
            uriTemplate: '/providers/{providerId}/ribs',
            uriVariables: [
                'providerId' => new Link(fromClass: Provider::class, toProperty: 'provider'),
            ],
            // read:false : pas de stade lecture du parent. Le Link toProperty
            // resoudrait l'enfant (SELECT ProviderRib ... WHERE provider = :id) et
            // casse en NonUniqueResult des >= 2 enfants. Le parent est rattache
            // manuellement par ProviderRibProcessor::linkParent (404 si absent).
            read: false,
            security: "is_granted('technique.providers.accounting.manage')",
            normalizationContext: ['groups' => ['provider:read:accounting']],
            denormalizationContext: ['groups' => ['provider:write:accounting']],
            processor: ProviderRibProcessor::class,
        ),
        new Patch(
            security: "is_granted('technique.providers.accounting.manage')",
            normalizationContext: ['groups' => ['provider:read:accounting']],
            denormalizationContext: ['groups' => ['provider:write:accounting']],
            provider: ProviderSubResourceItemProvider::class,
            processor: ProviderRibProcessor::class,
        ),
        new Delete(
            security: "is_granted('technique.providers.accounting.manage')",
            provider: ProviderSubResourceItemProvider::class,
            processor: ProviderRibProcessor::class,
        ),
    ],
)]
#[ORM\Entity]
#[ORM\Table(name: 'provider_rib')]
#[ORM\Index(name: 'idx_provider_rib_provider', columns: ['provider_id'])]
#[Auditable]
class ProviderRib implements TimestampableInterface, BlamableInterface, ProviderOwnedInterface
{
    use TimestampableBlamableTrait;

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

    #[ORM\ManyToOne(targetEntity: Provider::class, inversedBy: 'ribs')]
    #[ORM\JoinColumn(name: 'provider_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')]
    private ?Provider $provider = 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(['provider:read:accounting', 'provider:write:accounting'])]
    private ?string $label = null;

    // Bic/Iban bornent deja le format (et donc la longueur) : pas de Length redondant
    // calee sur la colonne (auto-exempte du miroir 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(['provider:read:accounting', 'provider:write:accounting'])]
    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(['provider:read:accounting', 'provider:write:accounting'])]
    private ?string $iban = null;

    // Ordre d'affichage du RIB (gere serveur, non expose au M3).
    #[ORM\Column(options: ['default' => 0])]
    private int $position = 0;

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

    public function getProvider(): ?Provider
    {
        return $this->provider;
    }

    public function setProvider(?Provider $provider): static
    {
        $this->provider = $provider;

        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;
    }
}
