import express from "express";
import cors from "cors";
import path from "path";
import { fileURLToPath } from "url";
import authRoutes from "./routes/auth.js";
import stampRoutes from "./routes/stamps.js";
import articleRoutes from "./routes/articles.js";
import musicRoutes from "./routes/music.js";
import redemptionRoutes from "./routes/redemption.js";
import adminRoutes from "./routes/admin.js";

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

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

app.use(cors());
app.use(express.json());

// Serve uploaded files
app.use("/uploads", express.static(path.join(__dirname, "../uploads")));

// Health check
app.get("/api/health", (_req, res) => {
  res.json({ success: true, data: { status: "ok" } });
});

// User-facing routes
app.use("/api/auth", authRoutes);
app.use("/api/stamps", stampRoutes);
app.use("/api/articles", articleRoutes);
app.use("/api/music", musicRoutes);
app.use("/api/redemption", redemptionRoutes);

// Admin routes
app.use("/api/admin", adminRoutes);

// Serve built web frontend in production (single-container deployment)
if (process.env.NODE_ENV === "production") {
  const webDist = path.join(__dirname, "../../web/dist");
  app.use(express.static(webDist));
  app.use((req, res, next) => {
    if (req.method !== "GET" && req.method !== "HEAD") return next();
    if (req.path.startsWith("/api") || req.path.startsWith("/uploads")) return next();
    res.sendFile(path.join(webDist, "index.html"));
  });
}

app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});
