const express = require("express");
const session = require("express-session");
const pgSession = require("connect-pg-simple")(session);
const path = require("path");
const { pool } = require("./config/database");
require("dotenv").config();

const app = express();
const PORT = process.env.PORT || 5000;

// Serve static files from /var/www/skyartshop
app.use(express.static("/var/www/skyartshop/public"));
app.use("/assets", express.static("/var/www/skyartshop/assets"));
app.use("/uploads", express.static("/var/www/skyartshop/uploads"));

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.use(
  session({
    store: new pgSession({
      pool: pool,
      tableName: "session",
      createTableIfMissing: true,
    }),
    secret: process.env.SESSION_SECRET || "skyart-shop-secret-2025",
    resave: false,
    saveUninitialized: false,
    cookie: {
      secure: process.env.NODE_ENV === "production" ? true : false,
      httpOnly: true,
      maxAge: 24 * 60 * 60 * 1000,
      sameSite: "lax",
      domain: process.env.NODE_ENV === "production" ? ".ddns.net" : "localhost",
    },
    proxy: true,
    name: "skyartshop.sid",
  })
);

app.use((req, res, next) => {
  res.locals.session = req.session;
  res.locals.currentPath = req.path;
  next();
});

// API Routes
const authRoutes = require("./routes/auth");
const adminRoutes = require("./routes/admin");
const publicRoutes = require("./routes/public");
const usersRoutes = require("./routes/users");

// Admin redirect - handle /admin to redirect to login (must be before static files)
app.get("/admin", (req, res) => {
  res.redirect("/admin/login.html");
});

app.get("/admin/", (req, res) => {
  res.redirect("/admin/login.html");
});

// API Routes
app.use("/api/admin", authRoutes);
app.use("/api/admin", adminRoutes);
app.use("/api/admin/users", usersRoutes);
app.use("/api", publicRoutes);

// Admin static files (must be after redirect routes)
app.use("/admin", express.static("/var/www/skyartshop/admin"));

// Root redirect to admin login
app.get("/", (req, res) => {
  res.redirect("/admin/login.html");
});

app.get("/health", (req, res) => {
  res.json({
    status: "ok",
    timestamp: new Date().toISOString(),
    database: "connected",
  });
});

app.use((req, res) => {
  res.status(404).json({ error: "Not found" });
});

app.use((err, req, res, next) => {
  console.error("Error:", err);
  res.status(500).json({ error: "Server error" });
});

app.listen(PORT, "0.0.0.0", () => {
  console.log("========================================");
  console.log("  SkyArtShop Backend Server");
  console.log("========================================");
  console.log(`🚀 Server running on http://localhost:${PORT}`);
  console.log(`📦 Environment: ${process.env.NODE_ENV || "development"}`);
  console.log(`🗄️  Database: PostgreSQL (${process.env.DB_NAME})`);
  console.log("========================================");
});

process.on("SIGTERM", () => {
  console.log("SIGTERM received, closing server...");
  pool.end(() => {
    console.log("Database pool closed");
    process.exit(0);
  });
});
