import { Request, Response, NextFunction } from "express";
import { GetClientAuthMiddleware } from "../middlewares/client.js";
import Stacker from "../middlewares/stacker.js";
import RequestError, { HttpStatusCode } from "../../helper/request_error.js";
import User from "../../models/user.js";

const PasswordAuth = Stacker(
   GetClientAuthMiddleware(true, true),
   async (req: Request, res: Response) => {
      let {
         username,
         password,
         uid,
      }: { username: string; password: string; uid: string } = req.body;
      let query: any = { password: password };
      if (username) {
         query.username = username.toLowerCase();
      } else if (uid) {
         query.uid = uid;
      } else {
         throw new RequestError(
            req.__("No username or uid set"),
            HttpStatusCode.BAD_REQUEST
         );
      }

      let user = await User.findOne(query);
      if (!user) {
         res.json({ error: req.__("Password or username wrong") });
      } else {
         res.json({ success: true, uid: user.uid });
      }
   }
);
export default PasswordAuth;
