const express = require("express");
const cors = require("cors");
require("dotenv").config();

const app = express();

// --- MIDDLEWARE  ---

const allowedOrigins = [
  "http://localhost:5013",
  "http://localhost:5014",
  "http://localhost:5015",
];

app.use(
  cors({
    origin: function (origin, callback) {
      // izinkan request tanpa origin (Postman, dll)
      if (!origin) return callback(null, true);

      if (allowedOrigins.includes(origin)) {
        callback(null, true);
      } else {
        callback(new Error("Not allowed by CORS"));
      }
    },
    methods: ["GET", "POST", "PUT", "DELETE"],
    credentials: true,
  }),
);

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

// --- IMPORT ROUTER ---
const routerAuth = require("./auth/route.js");
const routerUser = require("./user/route.js");
const routerProduk = require("./produk/route.js");
const routerKategori = require("./kategori/route.js");
const routerOrder = require("./order/route.js");

// --- USE ROUTER ---
app.use("/api/auth", routerAuth);
app.use("/api/user", routerUser);
app.use("/api/produk", routerProduk);
app.use("/api/kategori", routerKategori);
app.use("/api/order", routerOrder);

const PORT = 5033;
app.listen(PORT, () => {
  console.log(`Server berjalan di: http://localhost:${PORT}`);
});
