import { model, Schema, Types } from "mongoose";

export interface IUser {
  email: string;
  name?: string;
  password: string;
  role?: Types.ObjectId;
  avatar?: Types.ObjectId;
}

const validateEmail = (email: string) => {
  const re = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
  return re.test(email);
};

const schema = new Schema<IUser>(
  {
    email: {
      type: String, //mongoose type인 String으로 일반적인 string과는 겉으로는 대문자 차이
      rquired: true,
      unique: true,
      validate: [validateEmail, "이메일을 입력해주세요"],
    },
    name: { type: String },
    avatar: { type: Schema.Types.ObjectId, ref: "FileInfo" },
    password: { type: String, required: true, select: false },
    role: { type: Schema.Types.ObjectId, ref: "Role" },
  },
  {
    toJSON: {
      versionKey: false,
      transform(doc, ret, options) {
        delete ret.password;
      },
    },
  }
);

export default model<IUser>("User", schema);
