package gc.mda.kcg.domain.fleet;

import jakarta.persistence.*;
import lombok.*;
import org.hibernate.annotations.JdbcTypeCode;
import org.hibernate.type.SqlTypes;

import java.time.OffsetDateTime;
import java.util.UUID;

/**
 * 모선 확정 결과 (운영자 의사결정).
 * iran 백엔드의 후보 데이터(prediction이 생성)와 별도로 운영자 결정만 자체 DB에 저장.
 */
@Entity
@Table(name = "gear_group_parent_resolution", schema = "kcg",
        uniqueConstraints = @UniqueConstraint(columnNames = {"group_key", "sub_cluster_id"}))
@Getter @Setter @NoArgsConstructor @AllArgsConstructor @Builder
public class ParentResolution {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "group_key", nullable = false, length = 255)
    private String groupKey;

    @Column(name = "sub_cluster_id", nullable = false)
    private Integer subClusterId;

    @Column(name = "status", nullable = false, length = 30)
    private String status;  // UNRESOLVED, MANUAL_CONFIRMED, REVIEW_REQUIRED

    @Column(name = "selected_parent_mmsi", length = 20)
    private String selectedParentMmsi;

    @Column(name = "selected_parent_name", length = 200)
    private String selectedParentName;

    @Column(name = "confidence", columnDefinition = "numeric(7,4)")
    private java.math.BigDecimal confidence;

    @Column(name = "top_score", columnDefinition = "numeric(7,4)")
    private java.math.BigDecimal topScore;

    @Column(name = "second_score", columnDefinition = "numeric(7,4)")
    private java.math.BigDecimal secondScore;

    @Column(name = "score_margin", columnDefinition = "numeric(7,4)")
    private java.math.BigDecimal scoreMargin;

    @Column(name = "decision_source", length = 30)
    private String decisionSource;

    @Column(name = "stable_cycles", columnDefinition = "integer default 0")
    private Integer stableCycles;

    @Column(name = "rejected_candidate_mmsi", length = 20)
    private String rejectedCandidateMmsi;

    @JdbcTypeCode(SqlTypes.UUID)
    @Column(name = "approved_by")
    private UUID approvedBy;

    @Column(name = "approved_at")
    private OffsetDateTime approvedAt;

    @Column(name = "rejected_at")
    private OffsetDateTime rejectedAt;

    @Column(name = "manual_comment", columnDefinition = "text")
    private String manualComment;

    @Column(name = "created_at", nullable = false)
    private OffsetDateTime createdAt;

    @Column(name = "updated_at", nullable = false)
    private OffsetDateTime updatedAt;

    @PrePersist
    void prePersist() {
        OffsetDateTime now = OffsetDateTime.now();
        if (createdAt == null) createdAt = now;
        if (updatedAt == null) updatedAt = now;
        if (status == null) status = "UNRESOLVED";
    }

    @PreUpdate
    void preUpdate() {
        updatedAt = OffsetDateTime.now();
    }
}
