package dev.lions.unionflow.server.entity.mutuelle.parts;

import dev.lions.unionflow.server.api.enums.mutuelle.parts.StatutComptePartsSociales;
import dev.lions.unionflow.server.entity.BaseEntity;
import dev.lions.unionflow.server.entity.Membre;
import dev.lions.unionflow.server.entity.Organisation;
import jakarta.persistence.*;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.*;

import java.math.BigDecimal;
import java.time.LocalDate;

@Entity
@Table(name = "comptes_parts_sociales", indexes = {
        @Index(name = "idx_cps_numero", columnList = "numero_compte", unique = true),
        @Index(name = "idx_cps_membre", columnList = "membre_id"),
        @Index(name = "idx_cps_org", columnList = "organisation_id")
})
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@EqualsAndHashCode(callSuper = true)
public class ComptePartsSociales extends BaseEntity {

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "membre_id", nullable = false)
    private Membre membre;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "organisation_id", nullable = false)
    private Organisation organisation;

    @NotBlank
    @Column(name = "numero_compte", unique = true, nullable = false, length = 50)
    private String numeroCompte;

    @NotNull
    @Min(0)
    @Column(name = "nombre_parts", nullable = false)
    @Builder.Default
    private Integer nombreParts = 0;

    @NotNull
    @Column(name = "valeur_nominale", nullable = false, precision = 19, scale = 4)
    private BigDecimal valeurNominale;

    /** nombreParts × valeurNominale — mis à jour à chaque transaction */
    @NotNull
    @Column(name = "montant_total", nullable = false, precision = 19, scale = 4)
    @Builder.Default
    private BigDecimal montantTotal = BigDecimal.ZERO;

    @NotNull
    @Column(name = "total_dividendes_recus", nullable = false, precision = 19, scale = 4)
    @Builder.Default
    private BigDecimal totalDividendesRecus = BigDecimal.ZERO;

    @NotNull
    @Enumerated(EnumType.STRING)
    @Column(name = "statut", nullable = false, length = 30)
    @Builder.Default
    private StatutComptePartsSociales statut = StatutComptePartsSociales.ACTIF;

    @NotNull
    @Column(name = "date_ouverture", nullable = false)
    @Builder.Default
    private LocalDate dateOuverture = LocalDate.now();

    @Column(name = "date_derniere_operation")
    private LocalDate dateDerniereOperation;

    @Column(name = "notes", length = 500)
    private String notes;
}
