import dotenv from "dotenv";
import express from "express";
const app = express();
import path, { dirname, join } from "path";
import { fileURLToPath } from "url";
import bodyParser from "body-parser";
import fileUpload from "express-fileupload"; // important pkg for file upload
import cors from "cors";
import cookieParser from "cookie-parser";

// firebase admin push notification
import admin from "firebase-admin";
import serviceAccount from "./googlefirebasePushnotification.json"  with { type: "json" };
// Design Router
import designRoute from "./resources/Design/designRouter.js";
app.use(express.json({ limit: "50mb" }));
app.use(express.urlencoded({ extended: true, limit: "50mb" }));
//webhook call route according strip (webhook want raw data not json data)

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
});

app.use((req, res, next) => {
  if (req.originalUrl === "/api/order/webhook") {
    next();
  } else {
    express.json()(req, res, next);
  }
});
///////////////////////////////////////////////

app.use(cookieParser());

//handdle cores
app.use(cors());
// app.use(bodyParser.urlencoded({ extended: true }));
app.use("/api/design", designRoute);
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

// Define the path to the public folder where static files are located
const publicPath = join(__dirname, "public");

// Serve static files from the 'public' directory
app.use(express.static(publicPath));
app.use(
  fileUpload({
    useTempFiles: true,
    tempFileDir: join(publicPath, 'temp'), 
  })
);

// const { STRIPE_SECRET_KEY, WEBHOOK_SECRET_KEY } = process.env;
// import { Stripe } from "stripe";
// const stripe = new Stripe(STRIPE_SECRET_KEY, {
//   apiVersion: "2020-08-27",
// });
// app.post(
//   "/webhook",
//   express.raw({ type: "application/json" }),
//   (request, response) => {
//     const sig = request.headers["stripe-signature"];

//     const signatureParts = sig.split(",");

//     // Initialize variables to store extracted values
//     let t, v1, v0;

//     // Iterate over signature parts
//     signatureParts.forEach((part) => {
//       // Split each part by "=" to separate key and value
//       const [key, value] = part.split("=");

//       // Assign value to the corresponding variable based on the key
//       if (key === "t") {
//         t = value;
//       } else if (key === "v1") {
//         v1 = value;
//       } else if (key === "v0") {
//         v0 = value;
//       }
//     });

//     // Log the extracted values
//     // console.log("t:", t);
//     // console.log("v1:", v1);
//     // console.log("v0:", v0);

//     let event;
//     // console.log("sig", sig);
//     // console.log(typeof request.body);
//     // console.log("request.body", request.body);
//     // const concatenatedString = t + "." + JSON.stringify(request.body);
//     const requestBodyString = JSON.stringify(request.body);
//     const concatenatedString = `${t}.${requestBodyString}`;
//     console.log("concatenatedString", concatenatedString);

//     try {
//       event = stripe.webhooks.constructEvent(
//         concatenatedString,
//         sig,
//         "whsec_dc9b9084fc764c806c8c5c06dd91de1ee809e9c8deab6d56e8e3ef2fc9c30c67"
//       );
//       console.log(
//         "+++++++++++++++event-----------------++=",
//         event,
//         "=================="
//       );
//     } catch (err) {
//       response.status(400).send(`Webhook Error: ${err.message}`);
//       return;
//     }

//     // Handle the event
//     switch (event.type) {
//       case "payment_intent.succeeded":
//         console.log("event.data.object", event.data.object);
//         const paymentIntentSucceeded = event.data.object;
//         // Then define and call a function to handle the event payment_intent.succeeded
//         break;
//       // ... handle other event types
//       default:
//         console.log(`Unhandled event type ${event.type}`);
//     }

//     // Return a 200 response to acknowledge receipt of the event
//     response.send();
//   }
// );

//auth
import user from "./resources/user/userRoute.js";
import ProductRouter from "./resources/Products/ProductRoute.js";
import ProductManualRouter from "./resources/ProductMannual/ProductManualRoute.js";
//Businesses
// import BusinessRoute from "./resources/Businesses/BusinessRoute.js";

import orderRoute from "./resources/Orders/orderRoute.js";
import DepartureRouter from "./resources/Departure/DepartureRoute.js";
import InformationRoute from "./resources/Informations/InformationRoute.js";
import Testimonial from "./resources/Testimonials/TestimonialRoute.js";

import StateRouter from "./resources/setting/state/state_routes.js";
//
import LanguageRoute from "./resources/setting/Language/language_routes.js";
//purpose
import PurposeRoute from "./resources/setting/Purpose/Purpose_routes.js";
//SalesCoOrdinator Routes
import SalesCoOrdinatorRoute from "./resources/SalesCoOrdinators/SalesCoOrdinatorRoute.js";
//TerritoryManager Routes
import TerritoryManagerRoute from "./resources/TerritoryManagers/TerritoryManagerRoute.js";
// category Route
import categoryRoute from "./resources/Category/categoryRoutes.js";
import brandroute from "./resources/Brands/BrandsRoutes.js";
import RegistrationImageRoute from "./resources/RegistrationImage/RegistrationImageRoute.js";
import loginImageRoute from "./resources/LoginImage/LoginImageRoute.js";
import shopImageRoute from "./resources/ShopPageImage/ShopPageImageRoute.js";
import ContentRoute from "./resources/Content/ContentRoutes.js";
import UserAddressRoute from "./resources/userAddress/useAddressRoute.js";
import CurrencyRoute from "./resources/Currency/CurrencyRoute.js";
// RD Routes 
import RDRoute from './resources/RetailDistributor/RetailDistributerRoutes.js' 
//business_Type
// import Business_TypeRoute from "./resources/setting/Business_Type/Business_routes.js";

import ConfigRouter from "./resources/setting/Configration/Config_routes.js";

//specialties
import SpecialtiesRouter from "./resources/Specialties/SpecialtiesRoute.js";
import ShippingAddressRoute from "./resources/ShippingAddresses/ShippingAddressRoute.js";
import stripeRoute from "./resources/StripePayment/stripeRoute.js";

import SeoRoute from "./resources/SEO&Analytics/SEORouter.js";
// KYC route
import KycRoute from "./resources/KYC/KycRoutes.js";
//Affiliate Routes
import AffiliateRoute from "./resources/Affiliate&Coupon/Affiliate/AffiliateRoute.js";
//Blog Routes
import BlogRoute from "./resources/Blog/BlogRoute.js";
//Coupon Routes
import CouponRoute from "./resources/Affiliate&Coupon/Coupon/CouponRoute.js";
//short urls
// import ShortUrlRouter from "./resources/Businesses/Short_Urls/ShortUrlRoute.js";
//support Ticket
// attandance
import attendance from "./resources/Attendance/AttandanceRoute.js";
//leave
import leave from "./resources/Leaves/LeaveRoute.js";
// Notification
import notification from "./resources/Notification/notificationRoute.js"
//Inventory
import InventoryRoute from "./resources/Inventory/InventoryRoute.js";
import SalesRoute from "./resources/Sales/SalesRoute.js";

// PD Order place 

import PdOrderRoute from './resources/PD_Orders/pdOrderRoute.js'

import RDOrderRoute from "./resources/RD_Ordes/rdOrderRoutes.js"

import TaskRoute from "./resources/Task/TaskRoute.js";
// visit RD and PD
import VisitRDandPDRoute from "./resources/VisitRD&PD/VisitRD&PDRoute.js";
//Stock
import Stock from "./resources/Stock/StockRoute.js";
app.use("/api/v1", user);

//Product
app.use("/api", ProductRouter);
//Product Manual
app.use("/api/productmanual", ProductManualRouter);
//businesses
// app.use("/api/businesses", BusinessRoute);
// Design

// Category
app.use("/api/category", categoryRoute);
//Brand
app.use("/api/brand", brandroute);
// registration image
app.use("/api/registerImage", RegistrationImageRoute);
app.use("/api/loginImage", loginImageRoute);
app.use("/api/shopImage", shopImageRoute);
// Content
app.use("/api/content", ContentRoute);
// User Address
app.use("/api/user-address", UserAddressRoute);
app.use("/api/shipping/address", ShippingAddressRoute);
//SalesCoOrdinator Routes
app.use("/api/salescoordinator", SalesCoOrdinatorRoute);
// Kyc Routes
app.use("/api", KycRoute);

//TerritoryManager Routes
app.use("/api/territorymanager", TerritoryManagerRoute);
//Order
app.use("/api/order", orderRoute);
//Departure
app.use("/api/departure/", DepartureRouter);
//Information
app.use("/api/information/", InformationRoute);
//Complaints
app.use("/api/testimonial/", Testimonial);
//state
app.use("/api/state", StateRouter);
//language
app.use("/api/language", LanguageRoute);
//Purpose
app.use("/api/purpose", PurposeRoute);
app.use("/api/business", orderRoute);
//Currency Route
app.use("/api/currency", CurrencyRoute);
//config
app.use("/api/config", ConfigRouter);

app.use("/api/stripe", stripeRoute);

app.use("/api/seo", SeoRoute);

//Affiliates
app.use("/api/v1/affiliate", AffiliateRoute);

//Coupons
app.use("/api/v1/coupon", CouponRoute);
//Blog
app.use("/api/v1/blog", BlogRoute);
//attendance
app.use("/api/v1", attendance);
//leave
app.use("/api/v1", leave);

// notification route 
app.use("/api",notification)
// order routes 
app.use("/api",PdOrderRoute)
//Inventory
app.use("/api/inventory", InventoryRoute);
// Sales
app.use("/api/sales", SalesRoute);
//Task
app.use("/api/task", TaskRoute);
// RD Rotuts auth 
app.use("/api",RDRoute)
// RD Order routes 
app.use("/api",RDOrderRoute)
// visit RD and PD
app.use("/api", VisitRDandPDRoute);
//config specialty
// app.use("/api/config/specialty", SpecialtiesRouter);
//specialties
// app.use("/api/specialist", SpecialistRouter);
//appointments
// app.use("/api/appointment", AppointmentRouter);
//short urls
// app.use("/api/shorturl", ShortUrlRouter);
//Support
//Stock
app.use("/api", Stock);
// Email CMS
// app.use("/api", RegisterEmail);
export default app;
