import { Router, Request, Response, NextFunction } from "express";
import { InvalidParameterError } from "../errors/invalidParameterError";
import { COOKIE_TOKEN } from "../utils/constant";
import { errorCode500 } from "../utils/errors";
import { LoginControlleur } from "../controleurs/loginControleur";

export class LoginRouter {
  private _router: Router;
  private _loginControleur: LoginControlleur;

  constructor() {
    this._loginControleur = new LoginControlleur();
    this._router = Router();
    this.init();
  }

  get router() {
    return this._router;
  }

  public async login(req: Request, res: Response, next: NextFunction) {
    try {
      const email = req.body.email;
      const password = req.body.password;
      if (!email) {
        throw new InvalidParameterError("Le paramètre email est absent");
      }
      if (!password) {
        throw new InvalidParameterError("Le paramètre password est absent");
      }
      let user = await this._loginControleur.login(email, password);
      res.cookie(COOKIE_TOKEN, user.token);
      return res.redirect("/");
    } catch (error) {
      errorCode500(error, req, res);
    }
  }

  public async logout(req: Request, res: Response, next: NextFunction) {
    try {
      res.clearCookie(COOKIE_TOKEN);
      return res.redirect("/login");
    } catch (error) {
      errorCode500(error, req, res);
    }
  }

  init() {
    this._router.post("/login", this.login.bind(this));
    this._router.get("/logout", this.logout.bind(this));
  }
}

export const loginRouter = new LoginRouter();
