import dotenv from "dotenv";
dotenv.config(); // ✅ BILKUL PEHLI LINE - sab se upar

import express from "express";
import cookieParser from "cookie-parser";
import cors from "cors";
import mongoose from "mongoose";
import { connection } from "./database/dbconnection.js";
import { errorMiddleware } from "./middlewares/error.js";
import userRouter from "./route/userRouter.js";
import teacherRouter from "./route/teacherRouter.js";
import bookingRouter from "./route/booking.js";
import { removeUnverifiedAccounts } from "./automation/removeUnverifiedAccounts.js";
import path from "path";
import { fileURLToPath } from "url";
import paymentRoutes from "./route/payment.js";
import adminRouter from "./route/adminRouter.js";
import contactRoute from "./route/contact.js";

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

export const app = express(); // ✅ PEHLE app banao

app.use(
  cors({
    origin: "http://localhost:3000",
    credentials: true,
  }),
);

// ✅ Webhook ke liye raw body - baaki routes se PEHLE
app.use("/api/payments/webhook", express.raw({ type: "application/json" }));

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

// ✅ Sab routes yahan - app banne ke BAAD
app.use("/api/v1/user", userRouter);
app.use("/api/v1/teacher", teacherRouter);
app.use("/api/v1/booking", bookingRouter);
app.use("/api/v1/admin", adminRouter);
app.use("/api/v1/contact", contactRoute);

app.use("/api/payments", paymentRoutes); // ✅ payment route

app.get("/ping", (req, res) => {
  res.status(200).json({
    success: true,
    message: "Server Working Fine 👋",
  });
});

const reactAppPath = path.join(__dirname, "build");
app.use("/uploads", express.static("uploads"));
app.use(express.static(reactAppPath));

app.use((req, res) => {
  res.sendFile(path.join(reactAppPath, "index.html"));
});

removeUnverifiedAccounts();
connection();
app.use(errorMiddleware);
