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

export type AuditCounterDocument = HydratedDocument<AuditCounter>

// Atomic monotonic counter for AuditEvent.seq. A single document with
// `_id: 'audit_seq'` is incremented via findOneAndUpdate({_id}, {$inc: {n:1}}).
// Concurrent inserts each get a distinct sequence number; the chain integrity
// holds regardless of which commits to disk first.
@Schema({ collection: 'audit_counters', timestamps: { updatedAt: true, createdAt: false } })
export class AuditCounter {
  // Counter identifier — for now we only have 'audit_seq' but the same
  // collection could host other monotonic counters later.
  @Prop({ required: true, unique: true })
  _id!: string

  @Prop({ required: true, default: 0 })
  n!: number
}

export const AuditCounterSchema = SchemaFactory.createForClass(AuditCounter)
