import jwt from "jsonwebtoken";
import  bcrypt from "bcrypt";
import dotenv from "dotenv";
import { AuthPayload } from "../api/dtos/AuthPayload.js";

dotenv.config();
const { JWT_SECRET = "" } = process.env;

/**
 * Information on the current auth token containing the
 * token itself as well as its expiry date
 */
export class tokenInfo{
  constructor(token: string, expiryDate: Date){
    this.token = token;
    this.expiryDate = expiryDate;
  }
  token: string;
  expiryDate: Date;
}

/**
 * Responsible for handling of encrypted passwords and token handling
 */
export class encrypt {
  /**
   * Encrypts a password string
   * @param password Password string
   * @returns encrypted password string
   */
  static async encryptpass(password: string) {
    return bcrypt.hashSync(password, 12);
  }

  /**
   * Compares a plain text password to an encrypted password
   * @param password plain text password
   * @param hashPassword ecrypted password
   * @returns Boolean indicating whether both passwords are identical
   */
  static comparepassword(password: string, hashPassword: string) : boolean{
    return bcrypt.compareSync(password, hashPassword);
  }

/**
 * Generates an authentication token that will be valid for one day based on the payload provided 
 * @param payload AuthPayload containing the userId
 * @returns tokenInfo containing authentication token and expiryDate
 */
  static generateToken(payload: AuthPayload) : tokenInfo {
    let expiryDate = new Date();
    expiryDate.setDate(expiryDate.getDate() + 1); // 1 day
    const token = jwt.sign(payload, JWT_SECRET, { expiresIn: "1d" });
    return new tokenInfo(token, expiryDate);
  }

  /**
   * Verifys the token and decrypts the payload
   * @param token authentiction token
   * @returns Payload of the token
   */
  static verifyToken(token: string) : jwt.JwtPayload | string {
    return jwt.verify(token, JWT_SECRET);
  }
}
