import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { HydratedDocument, Types } from 'mongoose';
import { User } from '../../users/schemas/user.schema';

export type PasswordResetCodeDocument = HydratedDocument<PasswordResetCode>;

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

  @Prop({ required: true, select: false })
  codeHash!: string;

  @Prop({ required: true })
  expiresAt!: Date;

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

  @Prop({ default: false, index: true })
  verified!: boolean;

  @Prop({ default: false, index: true })
  used!: boolean;
}

export const PasswordResetCodeSchema = SchemaFactory.createForClass(PasswordResetCode);

PasswordResetCodeSchema.index({ userId: 1, used: 1, expiresAt: -1 });
PasswordResetCodeSchema.index({ expiresAt: 1 }, { expireAfterSeconds: 0 });
