import mongoose, { Schema, Document, Model } from "mongoose";
import { User } from "@calchat/shared";
import { IdVirtual } from "./types";

export interface UserDocument extends Omit<User, "id">, Document {
  toJSON(): User;
}

const UserSchema = new Schema<
  UserDocument,
  Model<UserDocument, {}, {}, IdVirtual>,
  {},
  {},
  IdVirtual
>(
  {
    email: {
      type: String,
      required: true,
      unique: true,
      lowercase: true,
      trim: true,
    },
    userName: {
      type: String,
      required: true,
      trim: true,
    },
    passwordHash: {
      type: String,
      required: true,
    },
  },
  {
    timestamps: true,
    virtuals: {
      id: {
        get() {
          return this._id.toString();
        },
      },
    },
    toJSON: {
      virtuals: true,
      transform: (_, ret: Record<string, unknown>) => {
        delete ret._id;
        delete ret.__v;
        delete ret.passwordHash;
        return ret;
      },
    },
  },
);

export const UserModel = mongoose.model<UserDocument>("User", UserSchema);
