package org.nstart.dep265.requestservice.entity

import com.fasterxml.jackson.databind.JsonNode
import jakarta.persistence.Column
import jakarta.persistence.Entity
import jakarta.persistence.EnumType
import jakarta.persistence.Enumerated
import jakarta.persistence.Id
import jakarta.persistence.Table
import jakarta.persistence.UniqueConstraint
import org.hibernate.annotations.JdbcTypeCode
import org.hibernate.type.SqlTypes
import java.time.LocalDateTime
import java.util.UUID

@Entity
@Table(
    name = "outbox_events",
    uniqueConstraints = [
        UniqueConstraint(
            name = "uk_outbox_events_event_type_aggregate_id",
            columnNames = ["event_type", "aggregate_id"],
        ),
    ],
)
class OutboxEventEntity(
    @Id
    @Column(name = "id", nullable = false)
    var id: UUID,

    @Column(name = "event_type", nullable = false, length = 128)
    var eventType: String,

    @Column(name = "aggregate_type", nullable = false, length = 64)
    var aggregateType: String,

    @Column(name = "aggregate_id", nullable = false)
    var aggregateId: UUID,

    @JdbcTypeCode(SqlTypes.JSON)
    @Column(name = "payload", nullable = false)
    var payload: JsonNode,

    @Enumerated(EnumType.STRING)
    @Column(name = "status", nullable = false, length = 32)
    var status: OutboxEventStatus,

    @Column(name = "created_at", nullable = false)
    var createdAt: LocalDateTime,

    /** Число выполненных попыток публикации. */
    @Column(name = "attempts", nullable = false)
    var attempts: Int = 0,

    /** Не раньше этого момента событие снова попадёт в выборку публикации (backoff). */
    @Column(name = "next_attempt_at", nullable = false)
    var nextAttemptAt: LocalDateTime = createdAt,

    @Column(name = "published_at")
    var publishedAt: LocalDateTime? = null,

    @Column(name = "error_message", columnDefinition = "TEXT")
    var errorMessage: String? = null,
)
