const express = require("express");
const swaggerUi = require("swagger-ui-express");
const swaggerDocument = require("./swagger-output.json");
const cors = require("cors");
const path = require("path");

const sessionConfig = require("./config/session");

// Route imports
const formRoutes = require("./routes/formRoutes");
const userRoutes = require("./routes/userRoutes");
const orgRoutes = require("./routes/admin/orgRoutes");
const departmentRoutes = require("./routes/admin/departmentRoutes");
const designationRoutes = require("./routes/admin/designationRoutes");
const serviceRoutes = require("./routes/admin/serviceRoutes");
const shiftRoutes = require("./routes/admin/shiftRoutes");
const categoryRoutes = require("./routes/admin/categoryRoutes");
const brandRoutes = require("./routes/admin/brandRoutes");
const subCategoryRoutes = require("./routes/admin/subCategoryRoutes");
const variantRoutes = require("./routes/admin/variantRoutes");
const productRoutes = require("./routes/admin/productRoutes");
const taskRoutes = require("./routes/taskRoutes");
const payrollRoutes = require("./routes/payrollRoutes");
const invoiceRoutes = require("./routes/invoiceRoutes");
const branchRoutes = require("./routes/branchRoutes");
const policyRoutes = require("./routes/policyRoutes");
const documentRoutes = require("./routes/documentRoutes");
const taxRoutes = require("./routes/admin/taxRoutes");
const discountRoutes = require("./routes/admin/discountRoutes");
// const attendanceRoutes = require("./routes/attendanceRoutes");
const expenseRoutes = require("./routes/accounts/expenseRoutes");
const paymentRoutes = require("./routes/accounts/paymentRoutes");
const statementRoutes = require("./routes/accounts/statementRoutes");
// const customerRoutes = require("./routes/admin/customerRoutes");
const notificationRoutes = require("./routes/notificationRoutes");
const formConfigRoutes = require("./routes/mobile/formConfigRoutes");
const patientRoutes = require("./routes/patientRoutes");
const dashboardRoutes = require("./routes/mobile/dashboardRoutes");
// const leaveRoutes = require("./routes/leaveRoutes");
const slotRoutes = require("./routes/slotRoutes");
const specializationRoutes = require("./routes/specializationRoutes");
const appointmentRoutes = require("./routes/appointmentRoutes");
const botDashboardRoutes = require("./routes/dashboardRoutes");
const roleRoutes = require("./routes/roleRoutes");
const roleRoutesLatest = require("./routes/admin//roleRoutes");
const specializationPublicRoutes = require("./routes/specializationPublicRoutes");
const slotPublicRoutes = require("./routes/slotPublicRoutes");
const appointmentPublicRoutes = require("./routes/appointmentPublicRoutes");
const branchPublicRoutes = require("./routes/branchPublicRoutes");
const patientPublicRoutes = require("./routes/patientPublicRoutes");
const doctorPublicRoutes = require("./routes/userPublicRoutes");
const rolePermissionsRoutes =require("./routes/rolePermissionsRoutes");

// Security & Procurement
// const qcRoutes = require("./routes/securityops/qcRoutes");
const blacklistRoutes = require("./routes/securityops/blacklistRoutes");
// const qcParamRoutes = require("./routes/securityops/qcParamRoutes");
const uomRoutes = require("./routes/securityops/uomRoutes");
const warehouseRoutes = require("./routes/securityops/warehouseRoutes");
const configurationRoutes = require("./routes/securityops/configurationRoutes");
const secdashboardRoutes = require("./routes/securityops/secdashboardRoutes");
// const stockRoutes = require("./routes/securityops/stockRoutes");
const permissionRoutes = require("./routes/permissionRoutes");
// const goodsRoutes = require("./routes/postgre/goodsRoutes");


// **Procurement Routes latest update on 27042026** 
const vendorRoutes = require("./routes/procurement/vendorRoutes");
const itemMasterRoutes = require("./routes/procurement/itemRoutes");
const requisitionRoutes = require("./routes/procurement/requisitionRoutes");
const rfqRoutes = require("./routes/procurement/rfqRoutes");
const purchaseOrderRoutes = require("./routes/procurement/purchaseorderRoutes");
const groupMasterRoutes = require("./routes/procurement/groupMasterRoutes");
const uploadProformaRoutes = require("./routes/procurement/uploadProformaRoutes");
const grnRoutes = require("./routes/procurement/grnRoutes");
const approvalRoutes = require("./routes/procurement/approvalRoutes");
const TermsRoutes = require("./routes/procurement/termsRoutes");
const purchaseInvoiceRoutes = require("./routes/procurement/purchaseInvoiceRoutes");


// 🔹 Postgre (Core ERP)
const vehicleRoutes = require("./routes/postgre/vehicleRoutes");
const parkingRoutes = require("./routes/postgre/parkingRoutes");
const visitorRoutes = require("./routes/postgre/visitorRoutes");
const qcRoutes = require("./routes/postgre/qcRoutes");
const qcParamRoutes = require("./routes/postgre/qcParamRoutes"); 
// 🔹 Attendance

 // 🔹 Sales start
const salesCustomerRoutes = require("./routes/sales/salesCustomerRoutes");
const salesproductRoutes = require("./routes/sales/productRoutes");
const salesCustomerPriceRoutes = require("./routes/sales/salesCustomerPriceRoutes");
const salesEnquiryRoutes = require("./routes/sales/salesEnquiryRoutes");
const salesQuotationsRoutes = require("./routes/sales/salesQuotationsRoutes");
const salesOrderRoutes = require("./routes/sales/salesOrderRoutes");
const salesInvoiceRoutes = require("./routes/sales/salesInvoiceRoutes");
const salesContractRoutes = require("./routes/sales/salesContractRoutes");
const salesReturnRoutes = require("./routes/sales/salesReturnRoutes");
const salesDashboard  = require("./routes/sales/salesDashboard")
const salesReportRoutes = require("./routes/sales/salesReportRoutes")
// Sales end

// HR MODULE STARTS
//hr and payrolls 
const employeeRoutes = require("./routes/hrandpayrollRoutes/employeeRoutes");
const employeeOnboardingRoutes = require("./routes/hrandpayrollRoutes/employeeOnboardingRoutes");
const employeeBenefitsRoutes = require("./routes/hrandpayrollRoutes/employeeBenefitsRoutes");
const attendanceManagementRoutes = require("./routes/hrandpayrollRoutes/attendanceManagementRoutes");
const shiftsRoutes = require("./routes/hrandpayrollRoutes/shiftsRoutes");
const shiftAssignedRoutes = require("./routes/hrandpayrollRoutes/shiftAssignedRoutes");
const assetRoutes = require("./routes/hrandpayrollRoutes/assetsRoutes");
const terminationRoutes = require("./routes/hrandpayrollRoutes/employeeTerminationRoutes");
const relievingRoutes = require("./routes/hrandpayrollRoutes/employeeRelievingRoutes");
const emppayrollRoutes=require("./routes/hrandpayrollRoutes/employeePayrollRoutes");
const deductionRoutes = require("./routes/hrandpayrollRoutes/deductionRoutes");
const payslipRoutes=require("./routes/hrandpayrollRoutes/payslipRoutes");
const roleRoutess=require("./routes/hrandpayrollRoutes/roleRoutes");
const providentFundRouter   = require("./routes/hrandpayrollRoutes/providentFundRoutes");
const healthInsuranceRouter = require("./routes/hrandpayrollRoutes/healthInsuranceRoutes");
const leaveGroupsRoutes = require("./routes/hrandpayrollRoutes/leaveGroupsRoutes");
const allowancePackagesRoutes = require("./routes/hrandpayrollRoutes/allowancePackagesRoutes");
const hrLetterRoutes = require("./routes/hrandpayrollRoutes/hrLetterRoutes");
const leaveRoutes = require("./routes/hrandpayrollRoutes/leaveRoutes");
const ShiftPlanner = require("./routes/hrandpayrollRoutes/ShiftPlannerRoutes");
const organizationProvidentFundRoutes = require("./routes/hrandpayrollRoutes/organizationProvidentFundRoutes");
// HR MODULE ENDS

//BOM
const bomRoutes = require("./routes/bom/bomRoutes");

//Inventory
const inwardRoutes = require("./routes/inventory/inwardRoutes");
const outwardRoutes = require("./routes/inventory/outwardRoutes");
const stockRoutes = require("./routes/inventory/stockRoutes");
const goodsRoutes = require("./routes/inventory/goodsRoutes");

// Accounts
const accountsPayableRoutes = require("./routes/accounts/accountsPayableRoutes");
const accountsReceivableRoutes = require("./routes/accounts/accountsReceivableRoutes");
const journalVoucherRoutes = require("./routes/accounts/vocherRoutes");
const budgetRoutes = require("./routes/accounts/budgetRoutes");
const chartOfAccountsRoutes = require("./routes/accounts/chartOfAccountsRoutes");
const bankReconciliationRoutes = require("./routes/accounts/bankReconciliationRoutes");
// Dispatch Routes
const dispatchRoutes = require("./routes/dispatch/dispatchRoutes"); 
const transportRoutes = require("./routes/dispatch/tranportRoutes");
const gatePassRoutes = require("./routes/dispatch/gatePassRoutes");

//organization
const organizationRoutes = require("./routes/organizationRoutes/organizationRoutes");

// production
const productionRoutes = require("./routes/production/productionRoutes");
const dailyConsumptionRoutes = require("./routes/production/dailyConsumptionRoutes");
const stockConsumptionRoutes = require("./routes/production/stockConsumptionRoutes");

const app = express();
app.use(
  cors({
    origin: process.env.CLIENT_URL, // Make sure this is set in .env
    methods: ["GET", "POST", "PUT", "PATCH", "DELETE"],
    allowedHeaders: ["Content-Type", "Authorization"],
    credentials: true,
  }),
);

// ====================== MIDDLEWARE ======================
app.use(express.json());
app.use(express.urlencoded({ extended: true, limit: "50mb" }));
app.use(sessionConfig);

app.set("trust proxy", true);

// Static uploads
app.use("/uploads", express.static(path.join(__dirname, "uploads")));

// Multer/Excel error handler
app.use((err, req, res, next) => {
  if (err.message?.includes("Excel")) {
    return res.status(400).json({ success: false, message: err.message });
  }
  next(err);
});


// ====================== ROUTES ======================

// Public routes first (if any)
app.use("/api/public/specializations", specializationPublicRoutes);
app.use("/api/public/slots", slotPublicRoutes);
app.use("/api/public/appointments", appointmentPublicRoutes);
app.use("/api/public/branches", branchPublicRoutes);
app.use("/api/public/patients", patientPublicRoutes);
app.use("/api/public", doctorPublicRoutes);

// Main API routes
app.use("/api/forms", formRoutes);
app.use("/api/users", userRoutes);
app.use("/api/roles", roleRoutes);

app.get("/debug", (req, res) => {
  res.send("OK");
});

app.use("/api/admin/org", orgRoutes);
app.use("/api/admin/department", departmentRoutes);
app.use("/api/admin/designation", designationRoutes);
app.use("/api/admin/service", serviceRoutes);
app.use("/api/admin/category", categoryRoutes);
app.use("/api/admin/brand", brandRoutes);
app.use("/api/admin/subcategory", subCategoryRoutes);
app.use("/api/admin/variants", variantRoutes);
app.use("/api/admin/products", productRoutes);
app.use("/api/admin/shifts", shiftRoutes);
app.use("/api/admin/taxes", taxRoutes);
app.use("/api/admin/discounts", discountRoutes);
app.use("/api/admin/specializations", specializationRoutes); 
app.use("/api/roleslatest",roleRoutesLatest);



// app.use("/api/customers", customerRoutes);
app.use("/api/tasks", taskRoutes);
// app.use("/api/attendance", attendanceRoutes);
// app.use("/api/leaves", leaveRoutes);
app.use("/api/slots", slotRoutes);
app.use("/api/appointments", appointmentRoutes);

app.use("/api/org/branches", branchRoutes);
app.use("/api/org/policies", policyRoutes);
app.use("/api/org/documents", documentRoutes);

// HR routs starts
app.use("/api/employee", employeeRoutes);
app.use("/api/emp-onboarding", employeeOnboardingRoutes);
app.use("/api/employee-benefits", employeeBenefitsRoutes);
app.use("/api/attendance", attendanceManagementRoutes);
app.use("/api/shifts", shiftsRoutes);
app.use("/api/shift-assignments", shiftAssignedRoutes);
app.use('/api/assets', assetRoutes);
app.use("/api/termination", terminationRoutes);
app.use("/api/relieving", relievingRoutes);
app.use("/api/payrolls", emppayrollRoutes);
app.use("/api/deductions", deductionRoutes);
app.use("/api/payslip", payslipRoutes);
app.use("/api/payrolls", payslipRoutes);
app.use("/api/role", roleRoutess);
app.use("/api/rolePermission", rolePermissionsRoutes);
app.use("/api/provident-fund", providentFundRouter);
app.use("/api/health-insurance", healthInsuranceRouter);
app.use("/api/leave-groups", leaveGroupsRoutes);
app.use("/api/allowance-packages", allowancePackagesRoutes);
app.use("/api/hr-letters", hrLetterRoutes);
app.use("/api/leaves", leaveRoutes);
app.use("/api/shift-planner",ShiftPlanner);
app.use("/api/organization-provident-fund", organizationProvidentFundRoutes);
// HR routs ends

// Accounts routes (use different base paths to avoid conflicts)
app.use("/api/accounts/payroll", payrollRoutes);
app.use("/api/accounts/invoice", invoiceRoutes);
app.use("/api/accounts/expense", expenseRoutes);
app.use("/api/accounts/payment", paymentRoutes);
app.use("/api/accounts/statement", statementRoutes);


// Dashboard & Mobile
app.use("/api/dashboard", botDashboardRoutes);
app.use("/api/mobile", dashboardRoutes);
app.use("/api/mobile", notificationRoutes);
app.use("/api/mobile", formConfigRoutes);

// Security & QC
// app.use("/api/qc", qcRoutes);
// app.use("/api/qcparams", qcParamRoutes);
app.use("/api/security", blacklistRoutes);
app.use("/api/uom", uomRoutes);
app.use("/api/warehouse", warehouseRoutes);
app.use("/api/config", configurationRoutes);
app.use("/api/security", secdashboardRoutes);
// app.use("/api/inventory", stockRoutes);
app.use("/api/permissions", permissionRoutes);
// app.use("/api/inward", inwardRoutes);

// **Procurement Vendor Routes** lat update on 27042026
app.use("/api/procurement/vendors", vendorRoutes);
app.use("/api/procurement/item-master", itemMasterRoutes);
app.use("/api/procurement/requisitions", requisitionRoutes);
app.use("/api/procurement/rfqs", rfqRoutes);
app.use("/api/procurement/purchase-orders", purchaseOrderRoutes);
app.use("/api/group-master", groupMasterRoutes);
app.use("/api/grn", grnRoutes);
app.use("/api/approvals", approvalRoutes);
app.use("/api/upload-Proforma", uploadProformaRoutes);
app.use("/api/purchase-terms", TermsRoutes); 
app.use("/api/procurement/purchase-invoices", purchaseInvoiceRoutes);

// Postgre routes
app.use("/api/security/vehicle", vehicleRoutes);
app.use("/api/park", parkingRoutes);
app.use("/api/visitor", visitorRoutes);
app.use("/api/employee", employeeRoutes);
app.use("/api/qualitycheck", qcRoutes);
app.use("/api/qcparams", qcParamRoutes);
app.use("/api/goods", goodsRoutes);

app.use("/api/customers", salesCustomerRoutes);
// app.use("/api/salesproducts", salesproductRoutes);
app.use("/api/sales-customer-price", salesCustomerPriceRoutes);
app.use("/api/sales-enquiry", salesEnquiryRoutes);
app.use("/api/salesquotations", salesQuotationsRoutes);
app.use("/api/emp-onboarding", employeeOnboardingRoutes);
app.use("/api/employee-benefits", employeeBenefitsRoutes);
app.use("/api/salesorder", salesOrderRoutes);
app.use("/api/salesInvoice", salesInvoiceRoutes);
app.use("/api/sales-contract", salesContractRoutes); 
app.use("/api/sales_return", salesReturnRoutes);
app.use("/api/dashboard", salesDashboard)
app.use("/api/sales-reports", salesReportRoutes);

app.use("/api/attendance", attendanceManagementRoutes);
app.use("/api/shifts", shiftsRoutes);
app.use("/api/shift-assignments", shiftAssignedRoutes);
app.use('/api/assets', assetRoutes);
app.use("/api/termination", terminationRoutes);
app.use("/api/relieving", relievingRoutes);
app.use("/api/payrolls", emppayrollRoutes);

// BOM
app.use("/api/bom", bomRoutes);

// Inventory routes
app.use("/api/inventory", stockRoutes);
app.use("/api/inward", inwardRoutes);
app.use("/api/outward", outwardRoutes);


// Accounts
app.use("/api/accounts-payable", accountsPayableRoutes);
app.use("/api/accounts-receivable", accountsReceivableRoutes);
app.use("/api/journal-vouchers", journalVoucherRoutes);
app.use("/api/budget", budgetRoutes);
app.use("/api/chart-of-accounts", chartOfAccountsRoutes);
app.use("/api/bank-reconciliation", bankReconciliationRoutes);

// Dispatch 
app.use("/api/dispatch", dispatchRoutes);
app.use("/api/transport", transportRoutes);
app.use("/api/gatePass", gatePassRoutes);

//organization
app.use("/api/organization", organizationRoutes);

// production
app.use("/api/production", productionRoutes)
app.use("/api/daily-consumption", dailyConsumptionRoutes);
app.use("/api/daily-consumption/", stockConsumptionRoutes);

// ====================== SWAGGER ======================
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerDocument));

// 404 Handler
app.use((req, res) => {
  res.status(404).json({
    success: false,
    message: `Route not found: ${req.method} ${req.originalUrl}`,
  });
});

// Global Error Handler
app.use((err, req, res, next) => {
  console.error("❌ Error:", err.stack);
  res.status(err.status || 500).json({
    success: false,
    message: err.message || "Internal Server Error",
  });
});

module.exports = app;
