import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { HydratedDocument, Types } from 'mongoose';
import { EngagementEventType } from '../engagement-event-type.enum';

export type EngagementEventDocument = HydratedDocument<EngagementEvent>;

@Schema({ timestamps: true, versionKey: false })
export class EngagementEvent {
  @Prop({ type: Types.ObjectId, required: true, index: true })
  userId!: Types.ObjectId;

  @Prop({ type: Types.ObjectId, required: true, index: true })
  postId!: Types.ObjectId;

  @Prop({ enum: EngagementEventType, required: true, index: true })
  type!: EngagementEventType;

  @Prop({ min: 0, max: 7_200_000, default: 0 })
  watchTimeMs!: number;

  @Prop({ min: 0, max: 100, default: 0 })
  progressPercent!: number;

  @Prop({ default: '', maxlength: 100 })
  sessionId!: string;

  @Prop({ type: Date, default: Date.now })
  occurredAt!: Date;
}

export const EngagementEventSchema = SchemaFactory.createForClass(EngagementEvent);
EngagementEventSchema.index({ userId: 1, occurredAt: -1 });
EngagementEventSchema.index({ userId: 1, postId: 1, occurredAt: -1 });
EngagementEventSchema.index({ postId: 1, type: 1, occurredAt: -1 });
EngagementEventSchema.index({ occurredAt: 1 }, { expireAfterSeconds: 180 * 24 * 60 * 60 });
