const { loginUser } = require("../services/auth.service");
const db = require("../db");

const LOCK_TIME_MINUTES = 5;

async function postLogin(req, res) {
  const { username, password } = req.body;

  try {
    const user = await loginUser(db, username, password, LOCK_TIME_MINUTES);

    /* req.session.user = user;
    res.redirect("/dashboard"); */

    req.session.user = user;

    // ✅ Trial Start setzen falls leer
    const [rowsSettings] = await db.promise().query(
      `SELECT id, trial_started_at, serial_number
   FROM company_settings
   ORDER BY id ASC
   LIMIT 1`,
    );

    const settingsTrail = rowsSettings?.[0];

    if (settingsTrail?.id && !settingsTrail.trial_started_at) {
      await db
        .promise()
        .query(
          `UPDATE company_settings SET trial_started_at = NOW() WHERE id = ?`,
          [settingsTrail.id],
        );
    }

    // ✅ Direkt nach Login check:
    const [rows] = await db
      .promise()
      .query(
        `SELECT serial_number, trial_started_at FROM company_settings ORDER BY id ASC LIMIT 1`,
      );

    const settings = rows?.[0];

    if (!settings?.serial_number) {
      return res.redirect("/serial-number");
    }

    res.redirect("/dashboard");
  } catch (error) {
    res.render("login", { error });
  }
}

function getLogin(req, res) {
  res.render("login", { error: null });
}

module.exports = {
  getLogin,
  postLogin,
};
