const mysql = require("mysql2");
const express = require("express");
const app = express();
const morgan = require("morgan");
const { readdirSync } = require("fs");
const cors = require("cors");
const path = require("path");

// เชื่อมต่อฐานข้อมูล MySQL
const db = mysql.createConnection({
  host: "node77730-project-65160024.th2.melon.cloud",
  port: "11818",
  user: "root",
  password: "YDGggh92238",
  database: "borrow_project",
});

// Middleware
app.use(morgan("dev"));
app.use(express.json({ limit: "20mb" }));
app.use(
  cors({
    origin: "*", // อนุญาตทุกโดเมน
  })
);

// โหลด router จากโฟลเดอร์ routes
const routesPath = path.join(__dirname, "routes");
readdirSync(routesPath).map((file) => {
  const routePath = path.join(routesPath, file);
  app.use("/api", require(routePath));
});

app.listen(3000, () => console.log("Server is running on port 3000"));

// เชื่อมต่อกับฐานข้อมูล
db.connect((err) => {
  if (err) {
    console.error("❌ ไม่สามารถเชื่อมต่อฐานข้อมูล:", err);
    return;
  }
  console.log("✅ เชื่อมต่อฐานข้อมูลสำเร็จ!");
});