import path from "path";
import fs from "fs";
import csv from "csv-parser";

export type User = {
  name: string;
  email: string;
  password: string;
  accessLevel: string;
};

/**
 * @returns {array} - Array of Objects containing user data
 */
export async function readUserCsv(): Promise<User[]> {
  return new Promise((resolve, reject) => {
    // Dynamic CSV location generation
    let csvPath = path.dirname(__dirname); // /login
    csvPath = path.dirname(csvPath); // /api
    csvPath = path.dirname(csvPath); // /app
    csvPath = path.dirname(csvPath); // /src
    csvPath = path.dirname(csvPath); // /[project]
    csvPath = path.dirname(csvPath); // /termor-tracker
    csvPath = path.join(csvPath, "src", "databases", "Users.csv");

    // Forms array for user data
    let results: User[] = [];
    // Reads data and adds it to results
    fs.createReadStream(csvPath)
      .pipe(csv())
      .on("data", (data) => results.push(data))
      .on("end", () => {
        resolve(results);
      })
      .on("error", (error) => {
        reject(error);
      });
  });
}

export function findUserByEmail(users: User[], email: string): User | undefined {
  return users.find((user) => user.email === email);
}

export async function passwordStrengthCheck(password: string): Promise<string> {
  if (password.length < 8) {
    return "short";
  } else if (password.length > 16) {
    return "long";
  }
  const lowercaseRegex = /[a-z]/;
  const uppercaseRegex = /[A-Z]/;
  const digitRegex = /\d/;
  const specialCharRegex = /[!@#$%^&*]/;
  if (!lowercaseRegex.test(password)) {
    return "no lower";
  } else if (!uppercaseRegex.test(password)) {
    return "no upper";
  } else if (!digitRegex.test(password)) {
    return "no digit";
  } else if (!specialCharRegex.test(password)) {
    return "no special";
  } else {
    return "secure";
  }
  return "end of function";
}

/**
 * Writes User objects to the Users.csv file
 * @param users {User[]} Array of User objects to write to the CSV file
 * @returns {Promise<void>}
 */
export async function writeUserCsv(users: User[]): Promise<void> {
  return new Promise((resolve, reject) => {
    // Dynamic CSV location generation
    let csvPath = path.dirname(__dirname); // /login
    csvPath = path.dirname(csvPath); // /api
    csvPath = path.dirname(csvPath); // /app
    csvPath = path.dirname(csvPath); // /src
    csvPath = path.dirname(csvPath); // /[project]
    csvPath = path.dirname(csvPath); // /termor-tracker
    csvPath = path.join(csvPath, "src", "databases", "Users.csv");

    // Prepare CSV data as a string
    const headers = "name,email,password,level"; // CSV headers
    const rows = users.map((user) => `${user.name},${user.email},${user.password},${user.accessLevel}`);
    const csvData = `${headers}\n${rows.join("\n")}`;

    // Write data to the file
    fs.writeFile(csvPath, csvData, (error) => {
      if (error) {
        reject(error); // Reject promise on error
      } else {
        resolve(); // Resolve the promise if successful
      }
    });
  });
}