package at.procon.dip.domain.ted.entity;

import at.procon.dip.architecture.SchemaNames;
import at.procon.dip.domain.document.entity.Document;
import at.procon.ted.model.entity.ContractNature;
import at.procon.ted.model.entity.NoticeType;
import at.procon.ted.model.entity.ProcedureType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Index;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.OneToOne;
import jakarta.persistence.PrePersist;
import jakarta.persistence.PreUpdate;
import jakarta.persistence.Table;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.util.UUID;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.JdbcTypeCode;
import org.hibernate.type.SqlTypes;

/**
 * Phase 3 TED-specific projection that sits on top of the generic DOC document root.
 */
@Entity
@Table(schema = SchemaNames.TED, name = "ted_notice_projection", indexes = {
        @Index(name = "idx_ted_proj_document", columnList = "document_id"),
        @Index(name = "idx_ted_proj_legacy_doc", columnList = "legacy_procurement_document_id"),
        @Index(name = "idx_ted_proj_package_identifier", columnList = "package_identifier"),
        @Index(name = "idx_ted_proj_publication_id", columnList = "publication_id"),
        @Index(name = "idx_ted_proj_notice_type", columnList = "notice_type"),
        @Index(name = "idx_ted_proj_buyer_country", columnList = "buyer_country_code"),
        @Index(name = "idx_ted_proj_publication_date", columnList = "publication_date")
})
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class TedNoticeProjection {

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

    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "document_id", nullable = false, unique = true)
    private Document document;

    @Column(name = "legacy_procurement_document_id", unique = true)
    private UUID legacyProcurementDocumentId;

    @Column(name = "package_identifier", length = 32)
    private String packageIdentifier;

    @Column(name = "notice_id", length = 100)
    private String noticeId;

    @Column(name = "publication_id", length = 50)
    private String publicationId;

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

    @Column(name = "ojs_id", length = 20)
    private String ojsId;

    @Column(name = "contract_folder_id", length = 100)
    private String contractFolderId;

    @Enumerated(EnumType.STRING)
    @Column(name = "notice_type", nullable = false, length = 50)
    @Builder.Default
    private NoticeType noticeType = NoticeType.OTHER;

    @Column(name = "notice_subtype_code", length = 10)
    private String noticeSubtypeCode;

    @Column(name = "sdk_version", length = 20)
    private String sdkVersion;

    @Column(name = "ubl_version", length = 10)
    private String ublVersion;

    @Column(name = "language_code", length = 10)
    private String languageCode;

    @Column(name = "issue_datetime")
    private OffsetDateTime issueDateTime;

    @Column(name = "publication_date")
    private LocalDate publicationDate;

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

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

    @Column(name = "buyer_country_code", length = 10)
    private String buyerCountryCode;

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

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

    @Column(name = "buyer_nuts_code", length = 10)
    private String buyerNutsCode;

    @Column(name = "buyer_activity_type", length = 50)
    private String buyerActivityType;

    @Column(name = "buyer_legal_type", length = 50)
    private String buyerLegalType;

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

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

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

    @Enumerated(EnumType.STRING)
    @Column(name = "contract_nature", nullable = false, length = 50)
    @Builder.Default
    private ContractNature contractNature = ContractNature.UNKNOWN;

    @Enumerated(EnumType.STRING)
    @Column(name = "procedure_type", length = 50)
    @Builder.Default
    private ProcedureType procedureType = ProcedureType.OTHER;

    @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 = "total_lots")
    @Builder.Default
    private Integer totalLots = 0;

    @Column(name = "max_lots_awarded")
    private Integer maxLotsAwarded;

    @Column(name = "max_lots_submitted")
    private Integer maxLotsSubmitted;

    @Column(name = "regulatory_domain", length = 50)
    private String regulatoryDomain;

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

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

    @Builder.Default
    @Column(name = "updated_at", nullable = false)
    private OffsetDateTime updatedAt = OffsetDateTime.now();

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

    @PreUpdate
    protected void onUpdate() {
        updatedAt = OffsetDateTime.now();
        generateNoticeUrl();
    }

    /**
     * Generates TED notice URL from publication_id.
     * Format: https://ted.europa.eu/en/notice/-/detail/{publication_id without leading zeros}
     */
    private void generateNoticeUrl() {
        if (publicationId != null && !publicationId.isEmpty()) {
            // Remove leading zeros from publication_id
            String cleanId = publicationId.replaceFirst("^0+", "");
            this.noticeUrl = "https://ted.europa.eu/en/notice/-/detail/" + cleanId;
        }
    }
}
