import { Response } from "express";
import NotFoundError from "./NotFoundError";
import { createLoginCookie } from "../cookies/create-cookies";
import { getUserDB } from "../db/dbFactory";

const userDB = getUserDB();

type userAccessType = {
  _id: any;
  emailVerified: boolean;
  email: string;
  botChecked: boolean;
};

const userUpdateCheck = async (
  res: Response,
  id: string,
  uuid: string | undefined
) => {
  const updatedUser = await userDB.getUserInfo(id);

  if (!updatedUser) throw new NotFoundError("Cannot find updated user auth");

  if (updatedUser.emailVerified) {
    const { accessToken, refreshToken } = await updatedUser.generateAuthToken(
      uuid
    );
    createLoginCookie(res, accessToken, refreshToken);
  }

  let strippedUser: userAccessType = {
    _id: updatedUser._id,
    emailVerified: updatedUser.emailVerified!,
    email: updatedUser.email,
    botChecked: false,
  };

  return strippedUser;
};

export default userUpdateCheck;
