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

export type AuditCheckpointDocument = HydratedDocument<AuditCheckpoint>

// Periodic signed anchor over the audit hash chain. CheckpointService writes
// one of these every N events (default 100) or every T minutes (default 5),
// whichever comes first. The verify endpoint walks events between
// consecutive checkpoints and re-validates each signature.
//
// `signature` is HMAC-SHA-256 of `${headSeq}:${headHash}:${at.toISOString()}`
// signed with AUDIT_SIGNING_KEY. Verification recomputes the HMAC; mismatch
// = checkpoint tampered with OR signing key rotated.
//
// Reason recorded for the audit trail's own audit trail: 'interval' (clock
// tick), 'threshold' (N events accumulated), 'startup' (first checkpoint
// after a process start), 'manual' (forced via operator UI).
@Schema({ collection: 'audit_checkpoints', timestamps: { createdAt: 'createdAt', updatedAt: false } })
export class AuditCheckpoint {
  @Prop({ required: true, index: true })
  at!: Date

  @Prop({ required: true, unique: true })
  headSeq!: number

  @Prop({ required: true })
  headHash!: string

  @Prop({ required: true })
  signature!: string

  // HMAC algorithm used. Future-proofing: when we move from HMAC-SHA-256 to
  // ed25519 in prod, the verifier picks the right primitive from this field
  // and we add a new value rather than breaking old checkpoints.
  @Prop({ default: 'HMAC-SHA-256' })
  sigAlg!: string

  @Prop({ enum: ['interval', 'threshold', 'startup', 'manual'], default: 'interval' })
  reason!: 'interval' | 'threshold' | 'startup' | 'manual'
}

export const AuditCheckpointSchema = SchemaFactory.createForClass(AuditCheckpoint)
