import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'
import { HydratedDocument } from 'mongoose'

export type IngestCursorDocument = HydratedDocument<IngestCursor>

// One row per ingest source. The worker reads `lastEventAt` on startup, pulls
// events with `created > lastEventAt`, then advances the cursor. Safe across
// platform-api restarts — the worker resumes where it left off.
@Schema({ collection: 'ingest_cursors', timestamps: true })
export class IngestCursor {
  @Prop({ required: true, unique: true, index: true })
  source!: string  // 'authentik' | 'ocis' | 'stalwart'

  @Prop({ required: true })
  lastEventAt!: Date

  // Optional — the external id of the last event we recorded. Useful when
  // multiple events share a timestamp; we use it as a tiebreaker so we don't
  // miss or double-record events that fall on the same millisecond.
  @Prop()
  lastEventId?: string
}

export const IngestCursorSchema = SchemaFactory.createForClass(IngestCursor)
