

import GlobalContext from "@/context/Provider";
import { AnyARecord } from "dns";
import React from "react";
import _superagent, { search } from "superagent";
const SuperagentPromise = require("superagent-promise");
const superagent = SuperagentPromise(_superagent, global.Promise);

// dev server
export const API_ROOT = process.env.NEXT_PUBLIC_DEV_API_URL;
export const BUCKET_ROOT = process.env.NEXT_PUBLIC_DEV_BUCKET_ROOT;

// production server 
// export const API_ROOT = process.env.NEXT_PUBLIC_API_ROOT;
// export const BUCKET_ROOT = process.env.NEXT_PUBLIC_BUCKET_ROOT;
export interface ChatResponse {
  success: boolean;
  reply: string;
  chatSessionId: string;
  isResolved: boolean;
}

export interface StartChatResponse {
  success: boolean;
  chatSessionId: string;
  message: string;
  isResolved: boolean;
}
export enum referralUserType {
  CUSTOMER = "customer",
  DRIVER = "driver",
  RESTAURANT = "restaurant"
}


const API_FILE_ROOT_MEDIUM = `${BUCKET_ROOT}/medium/`;
const API_FILE_ROOT_ORIGINAL = `${BUCKET_ROOT}/original/`;
const API_FILE_ROOT_SMALL = `${BUCKET_ROOT}/small/`;
const API_FILE_ROOT_AUDIO = `${BUCKET_ROOT}/audio/`;
const API_FILE_ROOT_VIDEO = `${BUCKET_ROOT}/video/`;
const API_FILE_ROOT_DOCUMENTS = `${BUCKET_ROOT}/document/`;
const API_FILE_ROOT_DB_BACKUP = `${BUCKET_ROOT}/backup/`;
const API_FILE_ROOT_DOCS = `${BUCKET_ROOT}/docs/`;
const encode = encodeURIComponent;
const responseBody = (res: any) => res.body;

let token: string | null = null;

const getCookieValue = (name: string): string | null => {
  if (typeof document === "undefined") return null;
  const match = document.cookie.match(new RegExp("(^|;\\s*)" + name + "=([^;]+)"));
  return match ? decodeURIComponent(match[2]) : null;
};

const getActiveToken = (): string | null => {
  if (typeof window !== "undefined") {
    return (
      getCookieValue("COOKIES_USER_ACCESS_TOKEN") ||
      getCookieValue("cookies_user_access_token") ||
      sessionStorage.getItem("token") ||
      localStorage.getItem("auth_token") ||
      token
    );
  }
  return token;
};

// Check if running in the browser before accessing sessionStorage or cookies
if (typeof window !== "undefined") {
  token = getActiveToken();
}

const tokenPlugin = (req: any) => {
  const activeToken = getActiveToken();
  if (activeToken) {
    req.set("Authorization", `Bearer ${activeToken}`);
  }
};
const tokenPluginOtpEmail = (req: any) => {
  if (typeof window !== "undefined" && sessionStorage.getItem("otpTokenEmail")) {
    req.set("Authorization", `Bearer ${sessionStorage.getItem("otpTokenEmail")}`);
  }
};
const tokenPluginOtpphone = (req: any) => {
  if (typeof window !== "undefined" && sessionStorage.getItem("otpTokenPhone")) {
    req.set("Authorization", `Bearer ${sessionStorage.getItem("otpTokenPhone")}`);
  }
};

const handleErrors = (err: any) => {
  if (err?.status === 401 || err?.status === 403) {
    console.error(err?.status === 401 ? "Unauthorized!" : "Forbidden/Blocked!", "Clearing session...");
    if (typeof window !== "undefined") {
      sessionStorage.clear();
      localStorage.clear();
      // Clear cookies manually
      document.cookie.split(";").forEach((c) => {
        document.cookie = c
          .replace(/^ +/, "")
          .replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/");
      });
      // Redirect to home if blocked or unauthorized to force login/signup buttons
      if (window.location.pathname !== "/home") {
        window.location.href = "/home";
      }
    }
  }
  throw err;
};

const requests = {
  del: (url: string) =>
    superagent.del(`${API_ROOT}${url}`).use(tokenPlugin).then(responseBody).catch(handleErrors),
  delMultiple: (url: string, body: any) =>
    superagent
      .del(`${API_ROOT}${url}`, body)
      .use(tokenPlugin)
      .then(responseBody).catch(handleErrors),
  get: (url: string) =>
    superagent.get(`${API_ROOT}${url}`).use(tokenPlugin).then(responseBody).catch(handleErrors),
  put: (url: string, body: any) =>
    superagent
      .put(`${API_ROOT}${url}`, body)
      .use(tokenPlugin)
      .then(responseBody).catch(handleErrors),
  patch: (url: string, body: any) =>
    superagent
      .patch(`${API_ROOT}${url}`, body)
      .use(tokenPlugin)
      .then(responseBody).catch(handleErrors),
  post: (url: string, body: any) =>
    superagent
      .post(`${API_ROOT}${url}`, body)
      .use(tokenPlugin)
      .then(responseBody).catch(handleErrors),
  verifypostE: (url: string, body: any) =>
    superagent
      .put(`${API_ROOT}${url}`, body)
      .use(tokenPlugin)
      .then(responseBody).catch(handleErrors),
  verifypostP: (url: string, body: any) =>
    superagent
      .post(`${API_ROOT}${url}`, body)
      .use(tokenPluginOtpphone)
      .then(responseBody).catch(handleErrors),
  file: (url: string, key: string, file: any, onProgress: any) =>
    superagent
      .post(`${API_ROOT}${url}`)
      .attach(key, file)
      .use(tokenPlugin)
      .on('progress', (event: any) => { if (onProgress) { onProgress(event); } })
      .then(responseBody).catch(handleErrors),


  upload: (url: string, key: string, file: any) =>
    superagent.post(`${API_ROOT}${url}`).attach(key, file).use(tokenPlugin).then(responseBody).catch(handleErrors),


};

// const Department = {
//   add: (info: any) => requests.post("departments", info),
//   delete: (id: string) => requests.del(`departments/${id}`),
//   edit: (info: any, id: string) => requests.patch(`departments/${id}`, info),
//   request: (info: any) => requests.post("departments/request", info),
//   listing: (type?: any) => requests.get(type ? `departments?${type}` : `departments`),
//   signUp: (info: any) => requests.post("user/signUp", info),
//   selectCompanyDepartment: (id: string, info: any) =>
//     requests.patch(`departments/company-admin-department/${id}`, info),
//   requestpatch: (id: string, info: any) => requests.patch(`departments/request/${id}`, info)
// };

const Alert_Activity = {
  add: (info: any) => requests.post("departments", info),
  request: (info: any) => requests.post("departments/request", info),
  listing: (type?: any) => requests.get(type ? `alert-activity?${type}` : `alert-activity`),
}

const Comment = {
  add: (id: string, info: any) => requests.post(`process/comment/${id}`, info),
  listing: (id: string) => requests.get(`process/comment/${id}`),
  update: (id: string, info: any) =>
    requests.patch(`process/comment/${id}`, info),
  doNothing: (id: string, info: any) =>
    requests.patch(`process/comment/do-nothing/${id}`, info),
  delete: (id: string) => requests.del(`process/comment/${id}`),
};
const Organization = {
  listingOrganisation: () => requests.get(`users/get-organizations`),
  getDepartment: () => requests.get(`users/search-department`),
  addOrganisation: (info: any) => requests.post(`users/create-organization`, info),
  switch: (info: any) => requests.post(`users/switch-organization`, info),
  update: (info: any) =>
    requests.patch(`organization/update`, info),
  invitation: (info: any) => requests.post("organization/invite-member", info),
  teamMmbers: () => requests.get(`organization/team-members`),

}
const Department = {
  get: () => requests.get(`organization/departments`),
  add: (info: any) => requests.post("organization/add-department", info),
  removeTeamMember: (id: any) => requests.del(`organization/remove-member/${id}`),
  delete: (id: string) => requests.del(`departments/${id}`),
  edit: (info: any, id: string) => requests.patch(`departments/${id}`, info),
  request: (info: any) => requests.post("departments/request", info),
  listing: (type?: any) => requests.get(type ? `departments?${type}` : `departments`),
  signUp: (info: any) => requests.post("user/signUp", info),
  selectCompanyDepartment: (id: string, info: any) =>
    requests.patch(`departments/company-admin-department/${id}`, info),
  requestpatch: (id: string, info: any) => requests.patch(`departments/request/${id}`, info)
}
const Food = {
  get: () => requests.get(`organization/departments`),
  add: (info: any, id: string) => requests.post(`food/${id}`, info),
  update: (info: any, id: string) => requests.patch(`food/${id}`, info),
  delete: (id: string) => requests.del(`departments/${id}`),
  edit: (info: any, id: string) => requests.patch(`departments/${id}`, info),
}

const page = {
  add: (info: any) => requests.post(`admin/pages`, info),
  listing: (q: string) => requests.get(`admin/pages?type=${q}`),
  update: (id: string, info: any) =>
    requests.patch(`admin/pages/${id}`, info),
  doNothing: (id: string, info: any) =>
    requests.patch(`process/comment/do-nothing/${id}`, info),
  delete: (id: string) => requests.del(`process/comment/${id}`),
};

const SuperAdmin = {
  login: (info: any) => requests.post("admin/login", info),
  setupCompProfile: (info: any) => requests.post("admin/company", info),
};
const Company = {
  add: (info: any) => requests.post("admin/company", info),
  profile: () => requests.get("admin/company"),
  updateCompany: (id: string, info: any) =>
    requests.patch(`admin/company/${id}`, info),
  addmember: (id: string, info: any) =>
    requests.post(`admin/company/${id}/admins`, info),
};
const Team = {
  addTeamMates: (info: any) => requests.post("user/teammates", info),
  invite: (info: any) => requests.post(`user/invite/member`, info),
  listing: () => requests.get(`user/members`),
  serachMember: (search: string) => requests.get(`user/members?limit=100&pagination=0${search ? `&search=${search}` : ""}`),
  deleteDeactivate: (info: any) =>
    requests.patch(`user/teammates/delete/deactivate`, info),
  add: (info: any) => requests.post("admin/team", info),
  profile: () => requests.get("admin/company"),
  updateCompany: (id: string, info: any) =>
    requests.patch(`admin/company/${id}`, info),
  addTeamMember: (info: any) => requests.post(`user/team-admin`, info),
  editTeamMember: (info: any, id: string) => requests.patch(`user/teammates/access/profile/${id}`, info),
  teammatesList: (q?: any) => requests.get(`user/teammates${q ? `?${q}` : ""}`),
  teamMateDetails: (id: any) => requests.get(`user/teammates/${id}`)
};


const Auth = {
  login: (info: any) => requests.post("auth/continue-with-phone", info),
  verifyOtp: (info: any) => requests.post("auth/verify-phone", info),
  verifyPhoneEmail: (info: any) => requests.post("auth/sent-otp", info),
  emailVerified: (info: any) => requests.put("auth/verify-email", info),
  phoneVerified: (info: any) => requests.put("auth/verify-edit-phone", info),
  Submit: () => requests.put("restaurant/submit/verification", ''),
  VerifyE: (info: any) => requests.verifypostE("auth/verify-email", info),
  VerifyP: (info: any) => requests.verifypostP("auth/verify/otp", info),
  logout: () => requests.del("auth/logout"),
  verifyPasswordOtp: (info: any) => requests.patch(`user/verify-otp`, info),
  resendOtp: (info: any) => requests.post("auth/resend-email-otp", info),
  profile: () => requests.get("auth/get-profile"),
  forgotPasswordVerify: (value: any) => requests.patch("users/forgot/verifyotp", value),
  forgotPassword: (value: any) => requests.patch("user/forgot-password", value),
  chnagePassword: (value: any) => requests.patch("user/change/password", value),
  resetPassword: (info: any) => requests.patch(`user/reset/password`, info),
  verifyEmailAdd: (info: any) => requests.patch("users/email/verify", info),
  socialLogin: (info: any) => requests.post("user/social-login", info),
  editProfile: (value: any) => requests.patch("user/profile", value),
  deleteAccount: (info: any) => requests.put(`auth/delete-account`, info),
  getReport: (q: any) => requests.get(`report-reason${q ? `?${q}` : ""}`),
  updateEmail: (info: any) => requests.patch(`user/change/email`, info),
  configuration: () => requests.get(`configuration`),
  coupon: (info?: string) => {
    let query = info || "";
    if (!query.includes("restaurant_id")) {
      if (typeof window !== "undefined") {
        const storedRestoId = localStorage.getItem("restoId");
        if (storedRestoId) {
          let restoId = storedRestoId;
          try {
            restoId = JSON.parse(storedRestoId);
          } catch (e) {
            restoId = storedRestoId;
          }
          if (restoId) {
            const params = new URLSearchParams(query);
            params.set("restaurant_id", restoId);
            query = params.toString();
          }
        }
      }
    }
    return requests.get(`order/available-coupons${query ? `?${query}` : ""}`);
  },
  applyCoupon: (info?: any) => requests.get(`order/apply-promo-code?${info}`),
};

const Profile = {
  getProfile: () => requests.get("auth/get-profile"),
  UpdateProfile: (data: any) => requests.put("auth/edit-profile", data),
  addAddress: (data: any) => requests.post("address", data),
  addCurrentAddress: (id: any) => requests.put(`address/update-to-current/${id}`, {}),
  getAddress: () => requests.get(`address`),
  updateAddress: (id: any, data: any) => requests.put(`address/${id}`, data),
  deleteAddress: (id: any) => requests.del(`address/${id}`),

}
const Earning = {
  getList: (q?: any) => requests.get(`earning/restaurant?${q}`),
}
const Favourite = {
  getList: (q?: any) => requests.get(`favourite?${q ? q : ''}`),
  toggle: (info: any) => requests.post("favourite/mark-as-fav/dislike", info),
}
const Orders = {
  get: (q?: any) => requests.get(`customer/your-orders?${q ? q : ''}`),
  getDetail: (id: any) => requests.get(`order/order-detail/${id}`),
  recentGet: (id?: any) => requests.get(`restaurant/recent/orders/${id}`),
  orderPlace: (info: any) => requests.post("order/order-placed", info),
  invoice: (id: any, q?: any) => requests.get(`order/invoice/${id}?${q}`),
  CancelOrder: (id: any, info?: any) => requests.patch(`order/${id}/cancel`, info ? `?${info}` : ""),
}
const Surcharge = {
  getCurrentActive: () => requests.get("surcharge/active/current"),
};
const Review = {
  restaurantRate: (info: any) => requests.post("review/rate-restaurant", info),
  driverRate: (info: any) => requests.post("review/rate/driver", info),
}
const Count = {
  get: (id: string) => requests.get(`vendor/order-count/${id}`),
}
const FoodList = {
  get: (q?: any) => requests.get(`food/find-all/for/vendor?${q}`),
  detail: (q?: any) => requests.get(`food/find/by/ids?${q}`),
}
const SearchList = {
  relevant: (q?: any) => requests.get(`customer/relevant-search?${q}`),
  detailed: (q?: any) => requests.get(`customer/detailed-search?${q}`),
}

const restaurant = {
  detail: (id: any, info: any) => requests.get(`order/restaurant-detail/${id}?${info ? info : ''}`),
  add: (info: any) => requests.post("restaurant", info),
  update: (id: string, info: any) => requests.put(`restaurant/${id}`, info),
  getQuick: (info: any) => requests.get(`customer/quick-picks?${info}`),
  getAll: (info: any, data: any) => requests.post(`customer/all-restaurant?${info}`, data),
  getOrders: (id: AnyARecord, info: any) => requests.get(`order/restaurant-menu/${id}?${info ? info : ''}`),
  getRecommendation: (q: any) => requests.get(`order/recommendations?${q}`),
  // getGroceryRestaurant: (info: any, data: any) => requests.post(`customer/all-restaurant?${info}`, { ...data, type: "grocery", category_parent_id: "6942abf0d7a579799dccba47" }),
  getGroceryRestaurant: (info: any, data: any) => requests.post(`customer/all-restaurant?${info}`, { type: "stores", ...data }),
  getModules: (id: string) => requests.get(`restaurant/modules/${id}`),
  getNearestPopularStores: (q: string) => requests.get(`customer/nearest-popular-stores?${q}`),
  getNearestStores: (q: string) => requests.get(`customer/nearest-stores?${q}`),
  getOrderAgain: (q?: string) => requests.get(`customer/order-again${q ? `?${q}` : ""}`),
  getCuisines: (q?: string) => requests.get(`customer/cuisines${q ? `?${q}` : ""}`),
}

const contact = {
  add: (info: any) => requests.post("contactus", info),
}
const report = {
  res: (info: any) => requests.post("report", info),
  order: (info: any) => requests.post("report/orders", info),
  customerVendorQuery: (info: any) => requests.post("customer/customer-vendor-query", info),
  customerQueriesList: (q?: string) => requests.get(`customer/customer-queries-list${q ? `?${q}` : ""}`),
}
const category = {
  get: (q?: any) => requests.get(`category${q ? `?${q}` : ""}`),
  add: (info: any) => requests.post("category", info),
  getAll: (q: any) => requests.get(`category${q ? `?${q}` : ""}`),
  getCustomerCategories: (q?: any) => requests.get(`customer/categories${q ? `?${q}` : ""}`),
}
const Common = {
  uploadFile: (key: string, file: any, onProgress?: any) =>
    requests.file(`image-upload`, key, file, onProgress),
  uploadSingle: (key: string, file: any) =>
    requests.upload(`image-upload`, key, file),

  uploadFileMultiple: (key: string, file: any, onProgress: any) =>
    requests.file(`Upload/do_spaces_file_upload_multiple`, key, file, onProgress),

  dbBackup: () => requests.post(`admin/db/backup`, {}),
  listing: (q?: string) => requests.get(`user/homepage${q ? "?" + q : ""}`),
};
const Chat = {
  create: (info: any) => requests.post("chat", info),
  list: (id: any) => requests.get(`chat?job_id=${id}`),
  del: (id: string) => requests.del(`chat/${id}`),
  delMultiple: (q: any) => requests.del(`chat${q ? `?${q}` : ""}`),
  edit: (id: string, info: any) => requests.patch(`chat/${id}`, info)
};

const Bank = {
  create: (info: any) => requests.post("bank", info),
  update: (info: any) => requests.put("bank", info),
  get: () => requests.get("bank"),
  // list: (id: any) => requests.get(`chat?job_id=${id}`),
  // del: (id: string) => requests.del(`chat/${id}`),
  // delMultiple: (q: any) => requests.del(`chat${q ? `?${q}` : ""}`),
  // edit:(id:string,info:any)=>requests.patch(`chat/${id}`,info)
};
const User = {

  organization: (type: any) => requests.get(`user/organization?type=${type}`),
  previlege: (info: any) => requests.get(`user/previlege?${info}`),
  update: (id: string, info: any) => requests.patch(`user/teammates/access/profile/${id}`, info),
  delete: () => requests.del(`user/account/delete`),
  logout: () => requests.del(`user/logout`),
  contact: (info: any) => requests.post(`user/contact-us`, info),
  content: () => requests.get(`admin/setting/page?type=tutorialAndOnboarding`)

};
const Notification = {
  listing: (q: string) => requests.get(`notification${q ? "?" + q : ""}`),
  singleRead: (id: string) => requests.patch(`notification/read/${id}`, {}),
  allRead: () => requests.patch(`notification/read/all`, {})
}

const DashBoard = {
  userGraph: (type: string) => requests.get(`user/graph?type=${type}`),
  userDashboard: (type: string) => requests.get(`user/dashboard?type=${type}`)

}
const Demo = {
  createProcess: (info: any) => requests.post("defaut/process", info),
  createContent: (info: any) => requests.post("defaut/image", info),
  updateContent: (id: string, info: any) =>
    requests.put(`defaut/process/${id}`, info),
  processList: () => requests.get(`defaut/process`),
  getContent: (id: string) => requests.get(`defaut/image?_id=${id}`),
  getContentAll: (id: string) => requests.get(`defaut/process/${id}`),
  updateVideoContent: (id: string, info: any) =>
    requests.patch(`defaut/process/${id}`, info),
};
const Process = {
  captureThumbnail: (info: any) => requests.post("process/captured-thumbnail", info),
  create: (info: any) => requests.post("process/initiate", info),
  start: (id: any) => requests.post(`process/start/${id}`, {}),
  editsteps: (id: any, info: any) => requests.post(`process/steps/update/${id}`, info),
  listing: (q?: any) => requests.get(`process/listing${q ? `?${q}` : ""}`),
  getById: (id: string) => requests.get(`process/details/${id}`),
  generateAI: (id: any, info: any) => requests.post(`process/genrate-description/${id}`, info),
  delete: (id: string) => requests.del(`process/delete/${id}`),
  deleteMultiple: (items: any) => requests.patch(`process/bulk/delete/archive`, items),
  flowChartUpdate: (id: any, payload: any) =>
    requests.patch(`process/update_flowchart/${id}`, payload),
  updateProcessAfterCreate: (id: string, info: any) =>
    requests.patch(`process/${id}`, info),
  processUpdate: (id: string, info: any) =>
    requests.patch(`process/details/${id}`, info),
  archieved: (id: string, info: any) =>
    requests.patch(`process/archive/${id}`, info),
  updateContent: (id: string, info: any) =>
    requests.patch(`process/update/document/${id}`, info),
  assign: (info: any) =>
    requests.patch(`process/assign`, info),
  assignProcess: (id: any, info: any) => requests.post(`user/teammates/assign/processess/${id}`, info),
  processComplete: (id: string, info: any) =>
    requests.patch(`process/complete/${id}`, info),
  processUploadVideo: (id: string, info: any) =>
    requests.patch(`process/add-video-audio/${id}`, info),
  createContent: (info: any) => requests.post("defaut/image", info),
  download: (info: any) => requests.post("process/download", info),
  userList: (type: string) => requests.get(`user/teammates?filter=${type}`),
  userListSearch: (q: any) => requests.get(`user/teammates${q ? `?${q}` : ""}`),
  processList: (q?: any) => requests.get(`process/listing${q ? `?${q}` : ""}`),
  getContent: (id: string) => requests.get(`defaut/image?_id=${id}`),
  getContentAll: (id: string) => requests.get(`defaut/process/${id}`),
  activity: (id: string) =>
    requests.get(`process/activities
/${id}`),
  updateVideoContent: (id: string, info: any) =>
    requests.patch(`defaut/process/${id}`, info),
  importexport: (q: string) =>
    requests.get(`process/import-export?${q}`)

};
const FILES = {
  audio: (filename: string) =>
    filename?.startsWith("http")
      ? filename
      : `${API_FILE_ROOT_AUDIO}${filename}`,
  video: (filename: string) =>
    filename?.startsWith("http")
      ? filename
      : `${API_FILE_ROOT_VIDEO}${filename}`,
  imageOriginal: (filename: string, alt: any) =>
    filename
      ? filename?.startsWith("http")
        ? filename
        : `${API_FILE_ROOT_ORIGINAL}${filename}`
      : alt,
  imageMedium: (filename: string, alt: any) =>
    filename
      ? filename?.startsWith("http")
        ? filename
        : `${API_FILE_ROOT_MEDIUM}${filename}`
      : alt,
  imageSmall: (filename: string, alt?: any) =>
    filename
      ? filename?.startsWith("http")
        ? filename
        : `${API_FILE_ROOT_SMALL}${filename}`
      : alt,
};

const Job = {
  createJob: (payload: any) => requests.post("jobs/create-request", payload),
  getLocations: (query: any) => requests.get(`jobs/fetch-location?location=${query}`),
  getJobQueue: (q: string) => requests.get(`jobs/fetch-request?status=running,scheduled&${q ? q : ""}`),
  deleteRequestJobs: (payload: any) => requests.patch(`jobs/delete-archive-request`, payload),
  deleteJobs: (payload: any) => requests.patch(`jobs/delete-archive`, payload),
  getTitle: (q: any) => requests.get(`jobtitle?pagination=0&limit=10&search=${q}`),
  getJobKeywords: (id: any, search: string) => requests.get(`jobtitle?job_title_id=${id}&pagination=0&limit=10&search=${search}`),
  listing: (id: any, q: string) => requests.get(`jobs/fetch-jobs/${id}?${q ? q : ""}`),
  changeStatus: (id: any, payload: any) => requests.patch(`jobs/update/job/status/${id}`, payload),
  getPercentage: (id: any) => requests.get(`jobs/request/pecentage/${id}`),
  details: (id: any) => requests.get(`jobs/fetch-job/${id}`),
  enhanced: (info: any) => requests.patch(`jobs/enhanced-with-ai`, info),
  export: (id: any) => requests.get(`jobs/fetch-request?export_ids=${id}`),
  exportResult: (req_id: any, id: any) => requests.get(`jobs/fetch-jobs/${req_id}?export_ids=${id}`),
};

const Automation = {
  getLists: (automationType: any, q: string) => requests.get(`automation?automation_type=${automationType}&${q ? q : ""}`),
  changeStatus: (id: string, info: any) => requests.patch(`automation/enable/disable/${id}`, info),
  generate: (id: string, info: any) => requests.patch(`automation/use/${id}`, info),
  details: (id: string) => requests.get(`automation/${id}`),
  export: (info: any) => requests.patch(`automation/export`, info)
};

const Wallet = {
  getWalletBalance: () => requests.get(`wallet/customer-wallet`),
  getTransactionHistory: (q?: any) => requests.get(`wallet/wallet-transactions?${q}`),
  addMoney: (payload: any) => requests.post(`wallet/wallet/add-money-intent`, payload),
  payWallet: (payload: any) => requests.post(`order/pay-with-wallet`, payload)
};

const Referrals = {
  getReferralHistory: (q?: any) => requests.get(`referrals/history?${q}`),
  getRegenerateCode: () => requests.get(`auth/regenerate-referral-code`),
  manageFinalReferral: () => requests.get(`customer/manage-referral-after-final-order`),
  getUserHistory: (type: referralUserType, page: number = 1, limit: number = 10) => requests.get(`referrals/history?type=${type}&page=${page}&limit=${limit}`)
}

const Sales = {
  getCertificationListing: () => requests.get("sales/certification-listing"),
};

const Banner = {
  getBanner: (info: any) => requests.get(`resturant-banner/user?${info}`),
  getAdminBanner: () => requests.get(`resturant-banner`),
  getAdminBannerGuest: () => requests.get(`resturant-banner/guest`),
  getHomePageBanner: (info: any) => requests.get(`resturant-banner/customer/home-page${info ? `?${info}` : ""}`),
  getVendorBanner: (restaurantId: string) => requests.get(`resturant-banner/customer/vendor/${restaurantId}`),
  trackBannerView: (id: string) => requests.post(`resturant-banner/${id}/view`, {}),
}

const LoyalityPoints = {
  getLoyality: () => requests.get(`loyality-points/wallet`),
  getHistory: (q?: any) => requests.get(`loyality-points/history?${q}`),
}

const notificationList = {
  listing: (q: any) => requests.get(`notificationr/notification-list?${q}`),
  deleteSingle: (id: string) => requests.del(`notificationr/delete-notification/${id}`),
  deleteAll: () => requests.del(`notificationr/delete-all-notifications`),
  markAllRead: () => requests.put(`notificationr/mark-all-as-read`, {}),
  markSingleRead: (id: any) => requests.put(`notificationr/mark-as-read/${id}`, {})
}

const chatBot = {
  sendMessage: (payload: any) => requests.post(`chat-bot/send`, payload),
  getMessage: (q: any) => requests.get(`chat-bot/chatbot-history/${q}`),
}

const featureList = {
  getNewlyAddedRestaurants: (q: any) => requests.get(`restaurant/features-list-guest?${q}`),
}

const Services = {
  getServices: () => requests.get(`restaurant/services`),
}

const Slots = {
  getRestaurantSlots: (id: any, q: any) => requests.get(`slot/slot-list/${id}?${q}`),
  bookSlot: (payload: any) => requests.post(`slot/booking`, payload),
  getBookingList: (q: any) => requests.get(`slot/booking-list?${q}`),
}


const Subscriptions = {
  getSubscription: (q: any) => requests.get(`order/subscriptions?${q}`),
  updateSubscription: (payload: any) => requests.put(`order/subscriptions`, payload),
  cancelSubscription: (id: string) => requests.del(`order/cancel-upcomming-order/${id}`),
}

const ConfigurationType = {
  listing: (q: any) => requests.get(`configuration?${q}`),
}

const Catering = {
  getCategoryList: (id: string) => requests.get(`catering-services/category-list/${id}`),
  getCateringServiceList: (id: string) => requests.get(`catering-services/plans/${id}`),
  createPlate: (payload: any) => requests.post(`catering-services/create-plate`, payload),
  getCateringServiceDetail: (q: any) => requests.get(`catering-services/plate-bookings?${q}`),
  updateStatus: (id: string, info: any) => requests.patch(`catering-services/plate-status/${id}`, info),
  payPendingAmount: (info: any, id: string) => requests.post(`catering-services/complete-booking-amount/${id}`, info)
}

const ParentCategory = {
  getParnetCategory: () => requests.get(`category-parent`),
}

const Cuisine = {
  getCuisine: () => requests.get(`cuisine`)
}

const PayTab = {
  getPaymentDetails: (id: string) => requests.get(`paytab/payment-details/${id}`),
};

const complaintChatBot = {
  sendMessage: (payload: any) => requests.post(`chatbot/message`, payload),
  startChat: () => requests.get(`chatbot/chat-start`),
};

const Grocery = {
  getGroceryList: (q: any) => requests.get(`item/list${q ? `?${q}` : ""}`),
  getGroupedByCategory: (q: any) => requests.get(`item/grouped-by-category${q ? `?${q}` : ""}`),
  getByCategory: (q: string) => requests.get(`item/by-category?${q}`),
  getDetail: (q: any) => requests.get(`grocery/grocery-detail${q ? `?${q}` : ""}`),
  getItemDetail: (id: string) => requests.get(`item/details/${id}`),
  orderPlace: (payload: any) => requests.post(`grocery/grocery-order`, payload),
  getGroceryOrderList: (q: any) => requests.get(`grocery/grocery-orders-details${q ? `?${q}` : ""}`),
  getSimilarItems: (q: any) => requests.get(`item/similar${q ? `?${q}` : ""}`),
  getItemsForCustomer: (id: string) => requests.get(`customer/items-for-customer/${id}`),
}


const apis = {
  Auth,
  Demo,
  Process,
  Company,
  restaurant,
  Automation,
  Comment,
  notificationList,
  Subscriptions,
  ConfigurationType,
  Organization,
  Alert_Activity,
  Department,
  page,
  User,
  Catering,
  ParentCategory,
  Slots,
  Team,
  Notification,
  Chat,
  Job,
  contact,
  Services,
  Grocery,
  API_ROOT,
  DashBoard,
  API_FILE_ROOT_DB_BACKUP,
  API_FILE_ROOT_SMALL,
  API_FILE_ROOT_MEDIUM,
  API_FILE_ROOT_DOCS,
  API_FILE_ROOT_ORIGINAL,
  API_FILE_ROOT_VIDEO,
  API_FILE_ROOT_DOCUMENTS,
  SuperAdmin,
  Common,
  Orders,
  Surcharge,
  featureList,
  Earning,
  BUCKET_ROOT,
  FILES,
  LoyalityPoints,
  Count,
  chatBot,
  Food,
  category,
  Bank,
  FoodList,
  Profile,
  SearchList,
  Favourite,
  Review,
  token,
  report,
  Wallet,
  Referrals,
  Sales,
  Banner,
  Cuisine,
  encode,
  PayTab,
  complaintChatBot,
  setToken: (_token?: any) => {
    token = _token;
  },
};

export default apis;