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

export type OutboxEventDocument = HydratedDocument<OutboxEvent>;

@Schema({ timestamps: true, versionKey: false })
export class OutboxEvent {
  @Prop({ required: true, index: true })
  eventType!: string;

  @Prop({ required: true, type: Object })
  payload!: Record<string, unknown>;

  @Prop({ required: true, default: 'pending', enum: ['pending', 'processed', 'failed'], index: true })
  status!: 'pending' | 'processed' | 'failed';

  @Prop({ required: true, default: 0, min: 0 })
  attempts!: number;

  @Prop({ default: '' })
  lastError!: string;

  @Prop({ type: Date, default: null, index: true })
  processedAt?: Date | null;
}

export const OutboxEventSchema = SchemaFactory.createForClass(OutboxEvent);
OutboxEventSchema.index({ status: 1, createdAt: 1 });
