const express = require("express");
const cors = require("cors");
const dotenv = require("dotenv");
const sequelize = require("./config/db"); // Import sequelize
const errorHandler = require("./middleware/errorHandler");
const cookieParser = require("cookie-parser");

dotenv.config();

// Ensure the database is connected
sequelize
  .authenticate()
  .then(() => console.log("Database connected successfully"))
  .catch((err) => console.error("Database connection error:", err));

const app = express();
app.use(express.json());
app.use(
  cors({
    origin: 'http://localhost:3000', // Allow only this origin
    credentials: true,               // If you're using cookies or Authorization headers
  })
);
app.use(cookieParser());

// ✅ Import Other Routes
app.use("/api/auth", require("./routes/auth")); // Replaced with authRoutes);
app.use("/api/members", require("./routes/members"));
app.use("/api/visitors", require("./routes/visitors"));
app.use("/api/events", require("./routes/eventRoutes"));
app.use("/api/prayers", require("./routes/prayerRoutes"));
app.use("/api/users", require("./routes/userRoutes"));
app.use("/api/inquiries", require("./routes/inquiriesRoutes"));
app.use("/api/cell-groups", require("./routes/cellGroupRoutes"));


// Error Handling Middleware
app.use(errorHandler);

module.exports = app;
