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

import at.procon.dip.architecture.SchemaNames;
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.ManyToOne;
import jakarta.persistence.PrePersist;
import jakarta.persistence.PreUpdate;
import jakarta.persistence.Table;
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;

/**
 * Mutable synchronization cursor/state per source system and scope.
 */
@Entity
@Table(schema = SchemaNames.TIME, name = "time_sync_state", indexes = {
        @Index(name = "idx_time_sync_state_source_system", columnList = "source_system"),
        @Index(name = "idx_time_sync_state_scope_key", columnList = "scope_key")
})
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class TimeSyncState {

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

    @Enumerated(EnumType.STRING)
    @JdbcTypeCode(SqlTypes.NAMED_ENUM)
    @Column(name = "source_system", columnDefinition = "TIME.time_source_system")
    private TimeSourceSystem sourceSystem;

    @Column(name = "scope_key", nullable = false, length = 255)
    private String scopeKey;

    @Builder.Default
    @Column(name = "enabled", nullable = false)
    private boolean enabled = true;

    @Column(name = "last_successful_sync_at")
    private OffsetDateTime lastSuccessfulSyncAt;

    @Column(name = "last_attempted_sync_at")
    private OffsetDateTime lastAttemptedSyncAt;

    @Column(name = "last_seen_watermark", length = 255)
    private String lastSeenWatermark;

    @Column(name = "last_seen_external_id", length = 255)
    private String lastSeenExternalId;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "last_run_id")
    private TimeSyncRun lastRun;

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

    @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();
    }

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