package at.procon.ted.model.entity;

import at.procon.dip.architecture.SchemaNames;
import jakarta.persistence.*;
import lombok.*;
import org.hibernate.annotations.JdbcTypeCode;
import org.hibernate.type.SqlTypes;

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

/**
 * JPA Entity representing a lot within a procurement notice.
 * A procurement document can have multiple lots.
 * 
 * @author Martin.Schweitzer@procon.co.at and claude.ai
 */
@Entity
@Table(schema = SchemaNames.TED, name = "procurement_lot", indexes = {
    @Index(name = "idx_lot_document", columnList = "document_id")
}, uniqueConstraints = {
    @UniqueConstraint(columnNames = {"document_id", "lot_id"})
})
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class ProcurementLot {

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

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "document_id", nullable = false)
    private ProcurementDocument document;

    /**
     * Lot identifier from the XML (e.g., "LOT-0001").
     */
    @Column(name = "lot_id", nullable = false, length = 50)
    private String lotId;

    /**
     * Buyer's internal reference for this lot.
     */
    @Column(name = "internal_id", columnDefinition = "TEXT")
    private String internalId;

    @Column(name = "title", columnDefinition = "TEXT")
    private String title;

    @Column(name = "description", columnDefinition = "TEXT")
    private String description;

    @Column(name = "cpv_codes", columnDefinition = "VARCHAR(100)[]")
    @JdbcTypeCode(SqlTypes.ARRAY)
    private String[] cpvCodes;

    @Column(name = "nuts_codes", columnDefinition = "VARCHAR(20)[]")
    @JdbcTypeCode(SqlTypes.ARRAY)
    private String[] nutsCodes;

    @Column(name = "estimated_value", precision = 20, scale = 2)
    private BigDecimal estimatedValue;

    @Column(name = "estimated_value_currency", length = 3)
    private String estimatedValueCurrency;

    @Column(name = "duration_value")
    private Double durationValue;

    @Column(name = "duration_unit", length = 20)
    private String durationUnit;

    @Column(name = "submission_deadline")
    private OffsetDateTime submissionDeadline;

    @Column(name = "eu_funded")
    @Builder.Default
    private Boolean euFunded = false;

    @Column(name = "created_at", nullable = false, updatable = false)
    @Builder.Default
    private OffsetDateTime createdAt = OffsetDateTime.now();

    @PrePersist
    protected void onCreate() {
        createdAt = OffsetDateTime.now();
    }
}
