

import GlobalContext from "@/context/Provider";
import { id } from "date-fns/locale";
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;



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;

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

const tokenPlugin = (req: any) => {
  if (token) {
    req.set("Authorization", `Bearer ${token}`);
  } else if (typeof window !== "undefined" && sessionStorage.getItem("token")) {
    req.set("Authorization", `Bearer ${sessionStorage.getItem("token")}`);
  }
  req.set("ngrok-skip-browser-warning", "true");
};
const tokenPluginOtpEmail = (req: any) => {
  if (typeof window !== "undefined" && sessionStorage.getItem("otpTokenEmail")) {
    req.set("Authorization", `Bearer ${sessionStorage.getItem("otpTokenEmail")}`);
  }
  req.set("ngrok-skip-browser-warning", "true");
};
const tokenPluginOtpphone = (req: any) => {
  if (typeof window !== "undefined" && sessionStorage.getItem("otpTokenPhone")) {
    req.set("Authorization", `Bearer ${sessionStorage.getItem("otpTokenPhone")}`);
  }
  req.set("ngrok-skip-browser-warning", "true");
};

const handleErrors = (err: any) => {
  if (err?.status === 401) {
    console.error("Unauthorized! Clearing session and redirecting to login...");
    if (typeof window !== "undefined") {
      const pendingToast = sessionStorage.getItem("pendingToast");
      sessionStorage.clear(); // Clear session storage
      if (pendingToast) {
        sessionStorage.setItem("pendingToast", pendingToast);
      }
      // Only redirect if not already on the login page to prevent infinite loop
      if (window.location.pathname !== "/auth/login") {
        window.location.href = "/auth/login";
      }
    }
  }
  throw err; // Rethrow the error so it can be handled where called
};

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
      .post(`${API_ROOT}${url}`, body)
      .use(tokenPluginOtpEmail)
      .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(`food/${id}`),
  edit: (info: any, id: string) => requests.patch(`departments/${id}`, info),
  available: (info: any, id: string) => requests.put(`food/is-available/${id}`, info),
  getFoodById: (id: string) => requests.get(`food/${id}`),
}

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),
  autoLogin: (info: any) => requests.post("auth/auto-login", 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),
  Submit: () => requests.put("restaurant/submit/verification", ''),
  VerifyE: (info: any) => requests.verifypostE("auth/verify/otp", 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.patch("user/email-resend-otp", info),
  profile: () => requests.get(`user/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),
  updateEmail: (info: any) => requests.patch(`user/change/email`, info),
  resUpdate: (q: any) => requests.put(`restaurant/go-online/offline?${q}`, {}),
  getReport: (q: any) => requests.get(`report-reason${q ? `?${q}` : ""}`),
};


const Profile = {
  getProfile: () => requests.get("auth/get-profile"),
}
const Earning = {
  getList: (q?: any) => requests.get(`earning/restaurant?${q}`),
}
const Orders = {
  get: (q?: any) => requests.get(`vendor/today-order?${q}`),
  recentGet: (id?: any) => requests.get(`restaurant/recent/orders/${id}`),
  create: (info: any) => requests.post(`vendor/order_create`, info),
  placed: (info: any) => requests.post(`order/order-placed`, info),
  update: (id: any, status: any) => requests.put(`vendor/order_status?order_id=${id}&status=${status}`, {}),
  readyupdate: (id: any, status: any, otp: any) => requests.put(`vendor/order_status?order_id=${id}&status=${status}&otp=${otp}`, {}),
  addMorePreparingTime: (orderId: string, time: number) => requests.put(`vendor/add-more-preparing-time?order_id=${orderId}&time=${time}`, {}),
  DownloadInvoice: (id: string, type: string) => requests.get(`order/invoice/${id}?type=${type}`)
}
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}`),
  addFoods: (id: any, info: any) => requests.post(`food/${id}/bulk-create`, info),
}


const restaurant = {
  add: (info: any) => requests.post("restaurant", info),
  update: (id: string, info: any) => requests.put(`restaurant/${id}`, info),
  restrauntType: (info: any) => requests.post(`auth/restaurant-type`, info),
  getCategories: (q: any) => requests.get(`restaurant/services?${q}`),
  getAmeneties: () => requests.get(`restaurant/amenities`),
  getHomeCookedServices: () => requests.get(`restaurant/home-cooked-services`),
}
const contact = {
  add: (info: any) => requests.post("contactus", info),
  faq: (q: any) => requests.get(`faq/for/apps?status=${q}`),
}

const category = {
  get: (q?: any) => requests.get(`category/for-vendor${q ? "?" + q : ""}`),
  list: (q?: any) => requests.get(`category${q ? "?" + q : ""}`),
  getById: (id: string) => requests.get(`category/${id}`),
  add: (info: any) => requests.post("category", info),
  request: (info: any) => requests.post("category/request", info),
  getRequests: (q?: any) => requests.get(`category/requests${q ? "?" + q : ""}`),
  update: (id: string, info: any) => requests.put(`category/${id}`, info),
  delete: (id: string) => requests.del(`category/by-vendor/${id}`),
  reorder: (info: any) => requests.put("category/reorder", info),
}
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),
  csvUpload: (file: any) =>
    requests.upload(`csv-upload`, 'file', file),
  importCSV: (token: string) =>
    requests.post(`item/upload-csv`, { csv_token: token }),

  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"),
  getVendorBankDetails: (id: string) => requests.get(`payment/vendor/bank-details/${id}`),
  getPayoutTable: (id: string, params?: { page?: number; limit?: number; search?: string }) => {
    const query = new URLSearchParams();
    if (params?.page) query.append('page', params.page.toString());
    if (params?.limit) query.append('limit', params.limit.toString());
    if (params?.search) query.append('search', params.search);
    const queryString = query.toString();
    return requests.get(`payment/vendor/payout-table/${id}${queryString ? `?${queryString}` : ''}`);
  },
  getTransactionLedger: (id: string, params?: { page?: number; limit?: number }) => {
    const query = new URLSearchParams();
    if (params?.page) query.append('page', params.page.toString());
    if (params?.limit) query.append('limit', params.limit.toString());
    const queryString = query.toString();
    return requests.get(`vendor/wallet/transaction-ledger/${id}${queryString ? `?${queryString}` : ''}`);
  },
  getPayoutSummary: (id: string) => requests.get(`payment/vendor/payout-summary/${id}`),
  requestWithdraw: (body?: any) => requests.post("withdraw/vendor/request", body || {}),
};

const Withdraw = {
  request: (body?: any) => requests.post("withdraw/vendor/request", body || {}),
};
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`),
  review: (q?: any) => requests.get(`review/vendor-review-listing${q ? "?" + q : ""}`)
};
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 NotificationVendor = {
  listing: (q: string) => requests.get(`notificationr/notification-list${q ? "?" + q : ""}`),
  singleRead: (id: string) => requests.put(`notificationr/mark-as-read/${id}`, {}),
  allRead: () => requests.put(`notificationr/mark-all-as-read`, {}),
  deleteAll: () => requests.del(`notificationr/delete-all-notifications`),
  deleteSingle: (id: string) => requests.del(`notificationr/delete-notification/${id}`)
}

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 Configuration = {
  getConfiguration: () => requests.get(`configuration`),
}

const Banner = {
  addBanner: (payload: any) => requests.post(`resturant-banner`, payload),
  getBanner: () => requests.get(`resturant-banner`),
  delBanner: (id: any) => requests.del(`resturant-banner/${id}`),
  getBannerById: (id: any) => requests.get(`resturant-banner/detail/${id}`),
  editBanner: (id: any, payload: any) => requests.put(`resturant-banner/${id}`, payload)
}

const Discount = {
  addDiscount: (payload: any) => requests.post(`restaurant/discount`, payload)
}

const Documents = {
  getDocuments: (q: any) => requests.get(`document/list${q ? `?${q}` : ""}`),
  getUploadedDocumets: (q: any) => requests.get(`document/uploaded-documents?${q}`),
  // UpdateDocumets:()
  uploadDocument: (payload: any) => requests.post(`document/submit`, payload),
}

const HomeCooked = {
  addHomeCookedMenu: (payload: any) => requests.post(`food/home-cooked-menu`, payload),
}

const Booking = {
  getBooking: (q: any) => requests.get(`slot/booking-list?${q}`),
  updateBooking: (info: any) => requests.put(`slot/booking-status`, info),
}

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

const Catering = {
  getCategoryList: (id: string) => requests.get(`catering-services/category-list/${id}`),
  addCateringService: (payload: any) => requests.post(`catering-services/plan`, payload),
  getCateringServiceList: (id: string) => requests.get(`catering-services/plans/${id}`),
  getPlanDetailById: (id: string) => requests.get(`catering-services/plans-details/${id}`),
  updateCateringService: (id: string, info: any) => requests.patch(`catering-services/plan/${id}`, info),
  deleteCateringService: (id: string) => requests.del(`catering-services/plans/${id}`),
  getCateringServiceDetail: (q: any) => requests.get(`catering-services/plate-bookings?${q}`),
  updateStatus: (id: string, info: any) => requests.patch(`catering-services/plate-status/${id}`, info),
  getPlateDetails: (id: string) => requests.get(`catering-services/plate-details/${id}`)
}

const ParentCategory = {
  addParentCategory: (payload: any) => requests.post(`category-parent`, payload),
  getParnetCategory: () => requests.get(`category-parent`),
  getDetailParentCategory: (id: any) => requests.get(`category-parent/${id}`),
  updateParentCategory: (id: string, info: any) => requests.patch(`category-parent/${id}`, info),
  deleteParentCategory: (id: any) => requests.del(`category-parent/${id}`)
}

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

const Item = {
  list: (q?: string) => requests.get(`item/list${q ? `?${q}` : ""}`),
  add: (payload: any) => requests.post(`item/add`, payload),
  delete: (id: string) => requests.del(`item/${id}`),
  details: (id: string) => requests.get(`item/details/${id}`),
  edit: (id: string, payload: any) => requests.put(`item/edit/${id}`, payload),
  available: (id: string, status: boolean | string) => requests.put(`item/is-available/${id}?status=${status}`, {}),
};

const Customer = {
  listing: (q?: string) => requests.get(`customer/listing${q ? `?${q}` : ""}`),
  queriesList: (q?: string) => requests.get(`customer/customer-queries-list${q ? `?${q}` : ""}`),
  replyQuery: (body: { query_id: string; reply: string }) => requests.patch(`customer/reply-customer-query`, body),
  itemsForCustomer: (body: { customer_id: string; other_cart_items: { id: string; no_of_quantity: number }[] }) => requests.patch(`customer/items-for-customer`, body),
};

const Report = {
  getSummary: () => requests.get(`vendor/report/vendor-summary`),
  getRevenueByWeekday: () => requests.get(`vendor/report/revenue-by-weekday`),
  getPopularItems: () => requests.get(`vendor/report/popular-items`),
  getRecentOrders: () => requests.get(`vendor/report/recent-orders`),
  getEarningsSalesDashboard: () => requests.get(`vendor/earnings-sales-dashboard`),
  getSalesAnalytics: (q?: string) => requests.get(`vendor/sales-analytics${q ? `?${q}` : ""}`),
  getOrdersAnalytics: (q?: string) => requests.get(`vendor/orders-analytics${q ? `?${q}` : ""}`),
  getItemAnalytics: (q?: string) => requests.get(`vendor/item-analytics${q ? `?${q}` : ""}`),
  downloadSalesReport: () => requests.get(`vendor/sales-report/download`),
};

const Driver = {
  getDriversList: (q?: string) => requests.get(`vendor/drivers${q ? `?${q}` : ""}`),
  removeDriver: (driverId: string) => requests.del(`vendor/drivers/${driverId}`),
};

const apis = {
  Auth,
  Customer,
  Demo,
  Process,
  Company,
  restaurant,
  Subscriptions,
  Documents,
  Automation,
  Comment,
  HomeCooked,
  Organization,
  Catering,
  Booking,
  ParentCategory,
  Alert_Activity,
  Department,
  page,
  User,
  Team,
  Notification,
  NotificationVendor,
  Chat,
  Job,
  Discount,
  contact,
  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,
  Earning,
  BUCKET_ROOT,
  FILES,
  Count,
  Food,
  category,
  Cuisine,
  Bank,
  Withdraw,
  FoodList,
  Profile,
  Configuration,
  token,
  encode,
  Banner,
  Item,
  Report,
  Driver,
  setToken: (_token?: any) => {
    token = _token;
  },
};

export default apis;