import sqlite3 from "sqlite3";
import express from "express";
import { fileURLToPath } from "url";
import { dirname, join } from "path";

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const app = express();

app.use(express.json());
app.use(express.static(__dirname));
app.use(express.static(join(__dirname, "session")));

const db = new sqlite3.Database("imposter.db");

// --- API- und andere spezifische Routes (bleiben oben) ---
app.get("/api/:sessionId/:username/createImposter", (req, res) => {
  const { sessionId, username } = req.params;

  db.all(`SELECT id FROM "${sessionId}"`, (err, row) => {
    if (err) {
      console.error(err);
      res.status(500).send("DB-Fehler");
      return;
    }
    console.log(row.length);
    createImposter(sessionId, row.length);
    res.status(200).send("ok");
  });
});

function createImposter(sessionId, userQty) {
  const ImposterId = Math.floor(Math.random() * userQty) + 1;
  console.log(sessionId, ImposterId);
  db.run(`UPDATE "${sessionId}" SET state = 1 WHERE id = ? `, [ImposterId]);
}

app.get("/api/:sessionId/:username/getImposter", (req, res) => {
  const { sessionId, username } = req.params;

  db.get(
    `SELECT state FROM "${sessionId}" WHERE user = ?`,
    [username],
    (err, rows) => {
      if (err) {
        console.error(err);
        res.status(500).send("DB-Fehler");
        return;
      }
      res.json(rows);
    },
  );
});

//liste an user zurückgeben
app.get("/api/user/:sessionId", (req, res) => {
  const { sessionId } = req.params;

  db.all(`SELECT user, ready, state FROM "${sessionId}"`, (err, rows) => {
    if (err) {
      console.error(err);
      return res.status(500).json({ error: err.message });
    }
    res.json(rows);
  });
});

app.put(`/api/words/add`, (req, res) => {
  const payload = req.body;

  console.log(payload.word, payload.imposterWord);

  db.serialize(() => {
    db.run(`CREATE TABLE IF NOT EXISTS words (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      word TEXT NOT NULL,
      imposterWord TEXT NOT NULL,
      inUse BOOL
      )`);

    db.run(
      `INSERT INTO words (word, imposterWord, inUse) VALUES (?, ?, ?)`,
      [payload.word, payload.imposterWord, 0],
      function (err) {
        if (err) {
          console.error("inserted words error:", err);
          return res.status(500).json({ error: err.message });
        }
        res.status(201).json({ id: this.lastID });
      },
    );
  });
});

app.put("/api/ready/:sessionId", (req, res) => {
  const { sessionId } = req.params;
  const payload = req.body;

  db.get(
    `SELECT ready FROM "${sessionId}" WHERE user = ?`,
    [payload.user],
    (err, row) => {
      if (err) {
        console.error(err);
      }
      console.log(row?.ready);
      if (row?.ready == 1) {
        db.run(
          `UPDATE "${sessionId}" SET ready = false WHERE user = ?`,
          [payload.user],
          res.status(200).json({ ready: false }),
        );
      } else {
        db.run(
          `UPDATE "${sessionId}" SET ready = true WHERE user = ?`,
          [payload.user],
          res.status(200).json({ ready: true }),
        );
      }
    },
  );
});

app.get("/api/getWords", (req, res) => {
  db.get(
    `SELECT word, imposterWord FROM words WHERE inUse = 1`,
    (err, rows) => {
      if (err) {
        console.log(err);
      }
      if (rows) {
        res.status(200).json(rows);
      } else {
        db.run(
          `UPDATE words SET inUse = 1 WHERE id = (SELECT id FROM words ORDER BY RANDOM() LIMIT 1)`,
        );
        res.status(201).json({ update: true });
        console.log("update");
      }
    },
  );
});
app.get("/api/reset/:sessionId", (req, res) => {
  const { sessionId } = req.params;

  db.run(`UPDATE "${sessionId}" SET state = 0 WHERE state = 1`);
  db.run(`UPDATE "${sessionId}" SET ready = 0 WHERE ready = 1`);
  db.run(`UPDATE words SET inUse = 0 WHERE inUse = 1`);
  return res.status(201).json({ success: true });
});

app.get("/:sessionId/:username/game", (req, res) => {
  res.sendFile(join(__dirname, "game", "game.html"));
});

app.get("/:sessionId/:username", (req, res) => {
  const { sessionId, username } = req.params;

  db.serialize(() => {
    db.run(`CREATE TABLE IF NOT EXISTS "${sessionId}" (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      user TEXT ,
      ready BOOL,
      state BOOL
      )`);

    db.run(`CREATE TABLE IF NOT EXISTS sessionState (
      sessionId TEXT PRIMARY KEY,
      state BOOL
      )`);
    db.run(
      `INSERT OR IGNORE INTO sessionState (sessionId, state) VALUES (?,?)`,
      [sessionId, 0],
    );

    db.get(
      `SELECT id FROM "${sessionId}" WHERE user = ?`,
      [username],
      (err, rows) => {
        if (err) {
          console.error(err);
        }
        if (rows) {
          console.log("user exists");
        } else {
          db.run(
            `INSERT OR IGNORE INTO "${sessionId}" (user, ready, state) VALUES (?, ?, ?)`,
            [username, 0, 0],
          );
        }
      },
    );
  });

  //beim neuladen der seite ready auf false setzen
  db.run(
    `UPDATE "${sessionId}" SET ready = false WHERE user = ?`,
    [username],
    () => {
      res.sendFile(join(__dirname, "session", "session.html"));
    },
  );
});

app.listen(3000, () => {
  console.log("Server is running");
});
