const express = require("express");
const cors = require("cors");
const dotenv = require("dotenv");
const session = require("express-session");
const bcrypt = require("bcryptjs");
const connectDB = require("./config/db");
const User = require("./models/User");

const authRoutes = require("./routes/authRoutes");
const employeeRoutes = require("./routes/employeeRoutes");
const payrollRoutes = require("./routes/payrollRoutes");
const reportRoutes = require("./routes/reportRoutes");

dotenv.config();

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

const seedDefaultUser = async () => {
  const username = "admin";
  const password = "admin123";
  const existingUser = await User.findOne({ username });

  if (!existingUser) {
    const hashedPassword = await bcrypt.hash(password, 10);
    await User.create({ username, password: hashedPassword });
    console.log("Default admin account created");
  }
};

app.use(express.json());
app.use(
  cors({
    origin: ["http://localhost:5173", "http://localhost:5174"],
    credentials: true
  })
);

app.use(
  session({
    secret: process.env.SESSION_SECRET || "epms_exam_secret",
    resave: false,
    saveUninitialized: false,
    cookie: {
      httpOnly: true,
      sameSite: "lax",
      secure: false,
      maxAge: 1000 * 60 * 60 * 2
    }
  })
);

app.get("/", (req, res) => {
  res.json({ message: "EPMS API is running" });
});

app.use("/api/auth", authRoutes);
app.use("/api/employees", employeeRoutes);
app.use("/api/payrolls", payrollRoutes);
app.use("/api/reports", reportRoutes);

const startServer = async () => {
  await connectDB();
  await seedDefaultUser();

  app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
  });
};

startServer();
