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

export type EmailVerificationCodeDocument = HydratedDocument<EmailVerificationCode>;

@Schema({ timestamps: true, versionKey: false })
export class EmailVerificationCode {
  @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 })
  used!: boolean;
}

export const EmailVerificationCodeSchema = SchemaFactory.createForClass(EmailVerificationCode);

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