import mysql from "mysql2";
import dotenv from "dotenv";
dotenv.config();

const pool = mysql
  .createPool({
    host: process.env.DB_HOST,
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
  })
  .promise();

export const getInfo = async () => {
  const [rows] = await pool.query("SELECT username FROM users;");
  const [rows2] = await pool.query("SELECT name FROM prize_draws;");

  if (rows.length > 0 && rows2.length > 0) {
    const users = rows.map((r) => r.username);
    const prize_draws = rows2.map((n) => n.name);
    return { users, prize_draws };
  } else {
    return { message: "No data found" };
  }
};

export const confirmUser = async (username) => {
  const [rows] = await pool.query("SELECT * FROM users WHERE username = ?", [
    username,
  ]);

  if (rows.length > 0) {
    const { first_name, last_name } = rows[0];
    const fullname = first_name + " " + last_name;

    // creating userTicketTable
    const d = new Date();

    const day = d.getDate();
    const month = d.getMonth() + 1;
    const year = d.getFullYear();
    const date = `${day}_${month}_${year}`;
    const tableName = `${username}_${date}`;

    const [createTable] = await pool.query(
      `CREATE TABLE IF NOT EXISTS ?? (
        id INT AUTO_INCREMENT PRIMARY KEY,
        Verlosung VARCHAR(100) NOT NULL,
        Vorname VARCHAR(100) NOT NULL,
        Nachname Varchar(100) NOT NULL,
        EMail Varchar(100) NOT NULL,
        Telefonnummer Varchar(100) NOT NULL,
        Lose INT NOT NULL,
        Schokolade BOOLEAN NOT NULL,
        Firmenname Varchar(100),
        Vorname_Geschaeftlich Varchar(100),
        Nachname_Geschaeftlich Varchar(100),
        EMail_Geschaeftlich Varchar(100),
        Telefonnummer_Geschaeftlich Varchar(100),
        Strasse_Hausnr Varchar(100),
        Plz_Ort Varchar(100),
        Zahlungsmethode Varchar(100),
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
      )`,
      [tableName],
    );

    if (createTable) {
      let nextID;
      const getNextID = async () => {
        const [rows] = await pool.query(
          `SELECT id FROM ?? ORDER BY id DESC LIMIT 1`,
          [tableName],
        );
        nextID = rows.length > 0 ? rows[0].id + 1 : 1;
      };
      await getNextID();
      return { success: true, nextID, tableName, fullname };
    } else {
      return { success: false, message: "Table creation failed", fullname };
    }
  } else {
    return null;
  }
};

export const newEntry = async (formData, username, prizeDraw) => {
  const confirmation = await confirmUser(username);

  if (!confirmation || !confirmation.success) {
    return { success: false, message: "User confirmation failed" };
  }

  const tableName = confirmation.tableName;

  const [result] = await pool.query(
    `INSERT INTO ?? (Verlosung, Vorname, Nachname, EMail, Telefonnummer, Lose, Schokolade, Firmenname, Vorname_Geschaeftlich, Nachname_Geschaeftlich, EMail_Geschaeftlich, Telefonnummer_Geschaeftlich, Strasse_Hausnr, Plz_Ort, Zahlungsmethode) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
    [
      tableName,
      prizeDraw,
      formData.firstName,
      formData.lastName,
      formData.email,
      formData.phoneNumber,
      formData.tickets,
      formData.chocolates,
      formData.companyName,
      formData.cmpFirstName,
      formData.cpmLastName,
      formData.cpmEmail,
      formData.cpmPhoneNumber,
      formData.street,
      formData.postalCode,
      formData.paymentMethod,
    ],
  );

  return { success: true, insertId: result.insertId };
};
