import { ObjectId } from "mongodb";
import User from "../../models/user-model";
import { IUserDB } from "../dbTypes";

// READ

class UserDB implements IUserDB {
  constructor() {}

  getUserInfo = async (userID: string) => {
    const user = await User.findOne({ _id: new ObjectId(userID) });
    return user;
  };

  findByEmail = async (email: string) => {
    const user = await User.findOne({ email });
    return user;
  };

  findByCreds = async (email: string, password: string) => {
    const userStatics = User as unknown as {
      findByCreds: (email: string, password: string) => Promise<any>;
    };
    return userStatics.findByCreds(email, password);
  };

  createUser = async (email: string, password: string) => {
    const user = new User({ email, password });
    await user.save();
    return user;
  };

  removeOldTokens = async (
    userID: string,
    uuid: string | undefined,
    minusTime: number,
    isTemp: boolean
  ) => {
    uuid = uuid ? uuid : "unknown";

    if (uuid === "unknown") return;

    const field = isTemp ? "tempTokens" : "tokens";

    await User.updateOne(
      { _id: new ObjectId(userID) },
      { $pull: { [field]: { uuid, time: { $lt: minusTime } } } }
    );
  };

  removeTempTokenByValue = async (userID: string, token: string) => {
    await User.updateOne(
      { _id: new ObjectId(userID) },
      { $pull: { tempTokens: { token } } }
    );
  };
}

export default UserDB;
