const express = require("express");
const sqlite3 = require("sqlite3").verbose();
const bodyParser = require("body-parser");
const shortid = require("shortid");
const path = require("path");

const app = express();
const PORT = process.env.PORT || 3000;
const basePath = "/nodeapp"; // 
const DELETE_PIN = "5858"; // 


app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, "public")));
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "views"));


const db = new sqlite3.Database("./urls.db", (err) => {
  if (err) return console.error(err.message);
  console.log("Connected to SQLite database.");
});


db.run(
  `CREATE TABLE IF NOT EXISTS urls (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    original_url TEXT NOT NULL,
    short_code TEXT NOT NULL UNIQUE
  )`
);


app.get(basePath + "/", (req, res) => {
  res.redirect(basePath + "/app");
});


app.get(basePath + "/app", (req, res) => {
  db.all("SELECT * FROM urls ORDER BY id DESC", [], (err, rows) => {
    if (err) return console.error(err.message);
    res.render("index", { urls: rows, basePath: basePath, req: req });
  });
});


app.post(basePath + "/shorten", (req, res) => {
  const original_url = req.body.original_url;
  const short_code = shortid.generate();

  db.run(
    `INSERT INTO urls(original_url, short_code) VALUES(?, ?)`,
    [original_url, short_code],
    function (err) {
      if (err) return console.error(err.message);
      res.redirect(basePath + "/app");
    }
  );
});


app.post(basePath + "/delete/:id", (req, res) => {
  const id = req.params.id;
  const pin = req.body.pin;

  if (pin !== DELETE_PIN) {
    return res.redirect(`${basePath}/app?msg=Invalid+PIN&type=error`);
  }

  db.run("DELETE FROM urls WHERE id = ?", [id], function (err) {
    if (err) {
      console.error(err.message);
      return res.redirect(`${basePath}/app?msg=Error+deleting+URL&type=error`);
    }
    res.redirect(`${basePath}/app?msg=URL+deleted+successfully&type=success`);
  });
});


app.get(basePath + "/:code", (req, res) => {
  const code = req.params.code;
  db.get("SELECT original_url FROM urls WHERE short_code = ?", [code], (err, row) => {
    if (err) return console.error(err.message);
    if (row) {
      res.render("redirect", { original_url: row.original_url });
    } else {
      res.send("<h1>URL not found</h1>");
    }
  });
});


app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
