const express = require("express");
const cors = require("cors");
const sqlite3 = require("sqlite3").verbose();
const app = express();
const session = require('express-session');
require("dotenv").config();

app.use(cors({
  origin: "http://localhost:5173",  // genau die Adresse deines Frontends
  credentials: true                 // Cookies erlauben
}));
app.use(express.json());
const bcrypt = require('bcrypt');
const db = new sqlite3.Database("../db.sqlite");
db.prepare(`CREATE TABLE IF NOT EXISTS users (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            username TEXT UNIQUE,
            password_hash TEXT)`).run();
const adminExists = db.get("SELECT * FROM users WHERE username = ?", ["admin"]);
if (!adminExists) {
  const hash = bcrypt.hashSync("admin", 10); // Passwort: admin
  db.prepare(`INSERT INTO users (username, password_hash) VALUES (?, ?)`).run('admin', hash);
}

app.use(session({
  secret: 'supergeheim', // Ändern in echte Secret
  resave: false,
  saveUninitialized: false,
  cookie: { secure: false }
}));


// Beispiel-Route: Link erstellen
app.post("/api/shorten", (req, res) => {
  const { original_url } = req.body;
  const id = Math.random().toString(36).substring(2, 8);
  db.run(
    "INSERT INTO links (id, original_url, created_at) VALUES (?, ?, datetime('now'))",
    [id, original_url],
    (err) => {
      if (err) return res.status(500).json({ error: err.message });
      res.json({ short_url: `http://localhost:3000/${id}`,
                 id: `${id}` });
    }
  );
});

// Beispiel-Redirect
app.get("/:id", (req, res) => {
  const id = req.params.id;
  db.get("SELECT original_url FROM links WHERE id = ?", [id], (err, row) => {
    if (row) res.redirect(row.original_url);
    else res.status(404).send("Not found");
  });
});


app.post('/api/login', (req, res) => {
  const { username, password } = req.body;

  db.get("SELECT * FROM users WHERE username = ?", [username], (err, user) => {
    if (err) {
      console.error("Datenbankfehler:", err);
      return res.status(500).json({ message: 'Interner Serverfehler' });
    }

    if (!user) {
      return res.status(401).json({ message: 'Benutzer existiert nicht' });
    }

    //console.log("Klartext-Passwort:", password);
    //console.log("Hash aus DB:", user.password_hash);

    const valid = bcrypt.compareSync(password, user.password_hash);
    if (!valid) return res.status(401).json({ message: 'Falsches Passwort' });

    req.session.user = { id: user.id, username: user.username };
    res.json({ success: true });
  });
});

app.get('/api/check-auth', (req, res) => {
  res.json({ loggedIn: !!req.session.user });
});

app.post('/api/logout', (req, res) => {
  req.session.destroy(() => res.json({ success: true }));
});

app.get('/', (req, res) => {
  res.json({ Name: "TRX SHORTLINK API" });
});




app.listen(3000, () => console.log("Server läuft auf http://localhost:3000"));
