package br.gov.sigefp.rh.domain;

import br.gov.sigefp.common.domain.AuditableEntity;
import jakarta.persistence.*;
import lombok.*;

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

/**
 * Entidade que registra um evento estruturado na vida laboral/carreira do
 * agente.
 * Substitui o AgentStatusHistory para fornecer dados ricos para folha e
 * auditoria.
 */
@Entity
@Table(name = "career_events", indexes = {
        @Index(name = "idx_career_event_agent", columnList = "agent_id"),
        @Index(name = "idx_career_event_type", columnList = "event_type"),
        @Index(name = "idx_career_event_date", columnList = "effective_date")
})
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class CareerEvent extends AuditableEntity {

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "agent_id", nullable = false)
    private Agent agent;

    @Enumerated(EnumType.STRING)
    @Column(name = "event_type", nullable = false, length = 50)
    private CareerEventType eventType;

    @Column(name = "effective_date", nullable = false)
    private LocalDate effectiveDate; // Data em que o evento passa a valer

    @Column(name = "publication_date")
    private LocalDate publicationDate; // Data de publicação no Boletim Oficial

    @Column(name = "document_ref", length = 100)
    private String documentRef; // Referência do Despacho ou documento legal

    // Snapshots da Carreira Salarial
    private UUID previousCategory;
    private UUID newCategory;

    private UUID previousGrade;
    private UUID newGrade;

    private UUID previousStep;
    private UUID newStep;

    // Snapshots Organizacionais
    private UUID previousOrgUnit;
    private UUID newOrgUnit;

    private UUID previousPosition;
    private UUID newPosition;

    // Snapshot Financeiro (Baseado no Decreto 12-A/94)
    @Column(precision = 19, scale = 2)
    private BigDecimal totalBaseAmount; // Rb (Remuneração Base)

    @Column(precision = 19, scale = 2)
    private BigDecimal cargoAmount; // 5/6 da remuneração base

    @Column(precision = 19, scale = 2)
    private BigDecimal exercicioAmount; // 1/6 da remuneração base

    @Column(length = 500)
    private String reason;

    @Column(name = "created_by_user")
    private String createdByUser;

    /**
     * Calcula a divisão 5/6 e 1/6 com base no valor base total.
     */
    public void calculateFinancialSplit(BigDecimal total) {
        if (total == null)
            return;
        this.totalBaseAmount = total;
        // 5/6 = (total * 5) / 6
        this.cargoAmount = total.multiply(BigDecimal.valueOf(5))
                .divide(BigDecimal.valueOf(6), 2, java.math.RoundingMode.HALF_UP);
        // 1/6 = total - 5/6 (para garantir que a soma feche perfeitamente)
        this.exercicioAmount = total.subtract(this.cargoAmount);
    }
}
