import doormileAxios, { DOORMILE_TOKEN_KEY, DOORMILE_USER_KEY } from 'utils/doormileAxios';

// API layer for the new Doormile Express admin backend (api.doormile.com/api/v1/admin/*).
// Mirrors the shape of pages/api/api.js (named async exports, one per endpoint) but talks
// to a different backend with a different envelope: { success, data } / { success, message }.
// See express-console-api.md at the repo root for the full reference this was built from.
// Not wired into any page yet — this is plumbing only.

const buildQuery = (params = {}) => {
  const usp = new URLSearchParams();
  Object.entries(params).forEach(([key, value]) => {
    if (value !== undefined && value !== null && value !== '') usp.append(key, value);
  });
  const qs = usp.toString();
  return qs ? `?${qs}` : '';
};

// ==============================|| Auth ||============================== //

export const loginAdmin = async (email, password) => {
  const response = await doormileAxios.post('/admin/login', { email, password });
  if (response.data.success) {
    localStorage.setItem(DOORMILE_TOKEN_KEY, response.data.token);
    localStorage.setItem(DOORMILE_USER_KEY, JSON.stringify(response.data.user));
  }
  return response.data;
};

export const logoutAdmin = () => {
  localStorage.removeItem(DOORMILE_TOKEN_KEY);
  localStorage.removeItem(DOORMILE_USER_KEY);
};

// ==============================|| Dashboard, profile, reports ||============================== //

export const getDashboard = async () => {
  const response = await doormileAxios.get('/admin/dashboard');
  return response.data.data;
};

// jupiter used fromdate/todate + applocationid (city); Doormile uses from/to
// and no city filter at all (filters by hubid instead — see
// jupiter2doormile.md §2.3/§6). Response carries by_location/by_hub/by_tenant/
// by_rider blocks per that doc, not documented in express-console-api.md.
export const getReports = async (from, to, tenantid, locationid, hubid) => {
  const response = await doormileAxios.get(`/admin/reports${buildQuery({ from, to, tenantid, locationid, hubid })}`);
  return response.data.data;
};

// Confirmed against jupiter2doormile.md (Status: Done) as the replacement for
// jupiter's getlocationsummary — per-tenant-site report breakdown. Not in
// express-console-api.md.
export const getLocationsSummary = async (tenantid, locationid, from, to) => {
  const response = await doormileAxios.get(`/admin/locations/summary${buildQuery({ tenantid, locationid, from, to })}`);
  return response.data.data;
};

export const getProfile = async () => {
  const response = await doormileAxios.get('/admin/profile');
  return response.data.data;
};

export const updateProfilePassword = async (current_password, new_password) => {
  const response = await doormileAxios.put('/admin/profile/password', { current_password, new_password });
  return response.data;
};

// ==============================|| App users (staff logins) ||============================== //

export const getAppUsers = async () => {
  const response = await doormileAxios.get('/admin/users');
  return response.data.data;
};

export const createAppUser = async (data) => {
  const response = await doormileAxios.post('/admin/users', data);
  return response.data;
};

export const updateAppUser = async (id, data) => {
  const response = await doormileAxios.put(`/admin/users/${id}`, data);
  return response.data;
};

export const deleteAppUser = async (id) => {
  const response = await doormileAxios.delete(`/admin/users/${id}`);
  return response.data;
};

// ==============================|| Partners (fleet / rider suppliers) ||============================== //

export const getPartners = async () => {
  const response = await doormileAxios.get('/admin/partners');
  return response.data.data;
};

export const createPartner = async (data) => {
  const response = await doormileAxios.post('/admin/partners', data);
  return response.data;
};

export const getPartner = async (id) => {
  const response = await doormileAxios.get(`/admin/partners/${id}`);
  return response.data.data;
};

export const updatePartner = async (id, data) => {
  const response = await doormileAxios.put(`/admin/partners/${id}`, data);
  return response.data;
};

export const deletePartner = async (id) => {
  const response = await doormileAxios.delete(`/admin/partners/${id}`);
  return response.data;
};

// ==============================|| Tenants (client companies) ||============================== //

export const getAdminTenants = async () => {
  const response = await doormileAxios.get('/admin/tenants');
  return response.data.data;
};

export const createAdminTenant = async (data) => {
  const response = await doormileAxios.post('/admin/tenants', data);
  return response.data;
};

export const getAdminTenant = async (id) => {
  const response = await doormileAxios.get(`/admin/tenants/${id}`);
  return response.data.data;
};

export const updateAdminTenant = async (id, data) => {
  // requiredeliveryotp is a pointer server-side — omit the key entirely to leave the setting alone.
  const response = await doormileAxios.put(`/admin/tenants/${id}`, data);
  return response.data;
};

export const deleteAdminTenant = async (id) => {
  const response = await doormileAxios.delete(`/admin/tenants/${id}`);
  return response.data;
};

export const getTenantLocations = async (tenantId) => {
  const response = await doormileAxios.get(`/admin/tenants/${tenantId}/locations`);
  return response.data.data;
};

export const createTenantLocation = async (tenantId, data) => {
  const response = await doormileAxios.post(`/admin/tenants/${tenantId}/locations`, data);
  return response.data;
};

export const updateTenantLocation = async (locationId, data) => {
  // Not nested under the tenant — PUT /admin/tenantlocations/:id.
  const response = await doormileAxios.put(`/admin/tenantlocations/${locationId}`, data);
  return response.data;
};

// ==============================|| Tenant customers (a client's own end customers) ||============================== //

export const getTenantCustomers = async () => {
  const response = await doormileAxios.get('/admin/tenantcustomers');
  return response.data.data;
};

export const createTenantCustomer = async (data) => {
  const response = await doormileAxios.post('/admin/tenantcustomers', data);
  return response.data;
};

export const getTenantCustomer = async (id) => {
  const response = await doormileAxios.get(`/admin/tenantcustomers/${id}`);
  return response.data.data;
};

export const updateTenantCustomer = async (id, data) => {
  const response = await doormileAxios.put(`/admin/tenantcustomers/${id}`, data);
  return response.data;
};

export const deleteTenantCustomer = async (id) => {
  const response = await doormileAxios.delete(`/admin/tenantcustomers/${id}`);
  return response.data;
};

// ==============================|| B2C app customers ||============================== //

export const getAdminCustomers = async () => {
  const response = await doormileAxios.get('/admin/customers');
  return response.data.data;
};

export const updateAdminCustomer = async (id, data) => {
  const response = await doormileAxios.patch(`/admin/customers/${id}`, data);
  return response.data;
};

// ==============================|| Hubs ||============================== //

export const getHubs = async () => {
  const response = await doormileAxios.get('/admin/hubs');
  return response.data.data;
};

export const createHub = async (data) => {
  const response = await doormileAxios.post('/admin/hubs', data);
  return response.data;
};

export const getHub = async (id) => {
  const response = await doormileAxios.get(`/admin/hubs/${id}`);
  return response.data.data;
};

export const updateHub = async (id, data) => {
  const response = await doormileAxios.put(`/admin/hubs/${id}`, data);
  return response.data;
};

export const deleteHub = async (id) => {
  // Soft delete server-side.
  const response = await doormileAxios.delete(`/admin/hubs/${id}`);
  return response.data;
};

// ==============================|| Vehicles ||============================== //

export const getVehicles = async () => {
  const response = await doormileAxios.get('/admin/vehicles');
  return response.data.data;
};

export const createVehicle = async (data) => {
  const response = await doormileAxios.post('/admin/vehicles', data);
  return response.data;
};

export const getVehicle = async (id) => {
  const response = await doormileAxios.get(`/admin/vehicles/${id}`);
  return response.data.data;
};

export const updateVehicle = async (id, data) => {
  const response = await doormileAxios.put(`/admin/vehicles/${id}`, data);
  return response.data;
};

export const deleteVehicle = async (id) => {
  // Soft delete server-side.
  const response = await doormileAxios.delete(`/admin/vehicles/${id}`);
  return response.data;
};

// ==============================|| Milers (riders) ||============================== //

export const getMilers = async () => {
  // Tenant-scoped server-side from the token — no tenantid param needed/accepted.
  const response = await doormileAxios.get('/admin/milers');
  return response.data.data;
};

export const createMiler = async (data) => {
  // configid defaults to 1001 server-side (the miler-app login partition) — do not override it.
  const response = await doormileAxios.post('/admin/milers', data);
  return response.data;
};

export const getMiler = async (id) => {
  const response = await doormileAxios.get(`/admin/milers/${id}`);
  return response.data.data;
};

export const updateMiler = async (id, data) => {
  const response = await doormileAxios.put(`/admin/milers/${id}`, data);
  return response.data;
};

export const blockMiler = async (id, data) => {
  const response = await doormileAxios.put(`/admin/milers/${id}/block`, data);
  return response.data;
};

export const assignMilerVehicle = async (id, data) => {
  const response = await doormileAxios.put(`/admin/milers/${id}/assign-vehicle`, data);
  return response.data;
};

export const notifyMiler = async (milerProfileId, title, message) => {
  const response = await doormileAxios.post(`/admin/milers/${milerProfileId}/notify`, { title, message });
  return response.data;
};

// Confirmed against jupiter2doormile.md (Status: Done — tested against a real
// request), not in express-console-api.md. jupiter used fromdate/todate;
// Doormile uses from/to (both YYYY-MM-DD). Aggregate rider KPI counts +
// current position (currentlatitude/currentlongitude/lastpingat per the doc —
// unconfirmed beyond those three field names).
export const getMilerSummary = async (applocationid, from, to, tenantid, hubid) => {
  const response = await doormileAxios.get(`/admin/milers/summary${buildQuery({ applocationid, from, to, tenantid, hubid })}`);
  return response.data.data;
};

// Replaces jupiter's `riderlogs` table — the rider's GPS/status ping history.
export const getMilerLogs = async (id, from, to, limit) => {
  const response = await doormileAxios.get(`/admin/milers/${id}/logs${buildQuery({ from, to, limit })}`);
  return response.data.data;
};

// No jupiter equivalent — new in Doormile.
export const getMilerActivity = async (id, from, to) => {
  const response = await doormileAxios.get(`/admin/milers/${id}/activity${buildQuery({ from, to })}`);
  return response.data.data;
};

// ==============================|| Bookings ||============================== //

export const getBookings = async (pageno, pagesize) => {
  const response = await doormileAxios.get(`/admin/bookings${buildQuery({ pageno, pagesize })}`);
  return response.data.data;
};

export const createExpressBooking = async (data) => {
  // tenantid is forced to the caller's own tenant server-side on client logins.
  // CityGate applies: pickup pincode prefix must be an open city (641/600/560/500/629).
  const response = await doormileAxios.post('/admin/expressbooking', data);
  return response.data;
};

export const createExpressBookingBulk = async (bookings) => {
  // Max 200 per call; response carries per-row results.
  const response = await doormileAxios.post('/admin/expressbooking/bulk', { bookings });
  return response.data;
};

export const getBooking = async (id) => {
  const response = await doormileAxios.get(`/admin/bookings/${id}`);
  return response.data.data;
};

export const assignMilerToBooking = async (id, data) => {
  const response = await doormileAxios.post(`/admin/bookings/${id}/assign-miler`, data);
  return response.data;
};

export const assignVehicleToBooking = async (id, data) => {
  const response = await doormileAxios.post(`/admin/bookings/${id}/assign-vehicle`, data);
  return response.data;
};

export const updateBookingStatus = async (id, data) => {
  const response = await doormileAxios.put(`/admin/bookings/${id}/status`, data);
  return response.data;
};

export const cancelBooking = async (id, data) => {
  const response = await doormileAxios.post(`/admin/bookings/${id}/cancel`, data);
  return response.data;
};

export const bulkCancelBookings = async (bookingIds) => {
  const response = await doormileAxios.post('/admin/bookings/bulk-cancel', { bookingIds });
  return response.data;
};

// Confirmed against jupiter2doormile.md (Status: Done), not in
// express-console-api.md.
export const getBookingTrack = async (id) => {
  const response = await doormileAxios.get(`/admin/bookings/${id}/track`);
  return response.data.data;
};

// ==============================|| Consignments ||============================== //

export const getConsignments = async () => {
  const response = await doormileAxios.get('/admin/consignments');
  return response.data.data;
};

// Confirmed against jupiter2doormile.md (Status: Done) — the actual GPS/status
// trail for a consignment, not in express-console-api.md.
export const getConsignmentLogs = async (id) => {
  const response = await doormileAxios.get(`/admin/consignments/${id}/logs`);
  return response.data.data;
};

export const getConsignment = async (id) => {
  const response = await doormileAxios.get(`/admin/consignments/${id}`);
  return response.data.data;
};

export const trackConsignment = async (trackingno) => {
  const response = await doormileAxios.get(`/admin/consignments/track/${trackingno}`);
  return response.data.data;
};

export const updateConsignmentStatus = async (id, data) => {
  const response = await doormileAxios.put(`/admin/consignments/${id}/status`, data);
  return response.data;
};

// ==============================|| Tripsheets (hub-to-hub transport) ||============================== //

export const getTripsheets = async () => {
  const response = await doormileAxios.get('/admin/tripsheets');
  return response.data.data;
};

export const createTripsheet = async (data) => {
  const response = await doormileAxios.post('/admin/tripsheets', data);
  return response.data;
};

export const getTripsheet = async (id) => {
  const response = await doormileAxios.get(`/admin/tripsheets/${id}`);
  return response.data.data;
};

export const addTripsheetItem = async (id, consignmentid) => {
  const response = await doormileAxios.post(`/admin/tripsheets/${id}/items`, { consignmentid });
  return response.data;
};

export const removeTripsheetItem = async (id, itemId) => {
  const response = await doormileAxios.delete(`/admin/tripsheets/${id}/items/${itemId}`);
  return response.data;
};

export const dispatchTripsheet = async (id) => {
  const response = await doormileAxios.put(`/admin/tripsheets/${id}/dispatch`);
  return response.data;
};

export const arriveTripsheet = async (id) => {
  const response = await doormileAxios.put(`/admin/tripsheets/${id}/arrive`);
  return response.data;
};

// ==============================|| Pricing ||============================== //

export const getAdminPricing = async () => {
  const response = await doormileAxios.get('/admin/pricing');
  return response.data.data;
};

export const createAdminPricing = async (data) => {
  const response = await doormileAxios.post('/admin/pricing', data);
  return response.data;
};

export const updateAdminPricing = async (id, data) => {
  const response = await doormileAxios.put(`/admin/pricing/${id}`, data);
  return response.data;
};

export const deleteAdminPricing = async (id) => {
  const response = await doormileAxios.delete(`/admin/pricing/${id}`);
  return response.data;
};

export const simulatePricing = async (data) => {
  const response = await doormileAxios.post('/admin/pricing/simulate', data);
  return response.data;
};

export const quotePricing = async (data) => {
  // Same handler as simulate.
  const response = await doormileAxios.post('/admin/pricing/quote', data);
  return response.data;
};

export const getDoormilePricing = async () => {
  const response = await doormileAxios.get('/admin/doormile-pricing');
  return response.data.data;
};

export const createDoormilePricing = async (data) => {
  const response = await doormileAxios.post('/admin/doormile-pricing', data);
  return response.data;
};

export const updateDoormilePricing = async (id, data) => {
  const response = await doormileAxios.put(`/admin/doormile-pricing/${id}`, data);
  return response.data;
};

export const deleteDoormilePricing = async (id) => {
  // Soft delete server-side.
  const response = await doormileAxios.delete(`/admin/doormile-pricing/${id}`);
  return response.data;
};

// ==============================|| Exceptions ||============================== //

export const getExceptions = async () => {
  const response = await doormileAxios.get('/admin/exceptions');
  return response.data.data;
};

export const createException = async (data) => {
  const response = await doormileAxios.post('/admin/exceptions', data);
  return response.data;
};

export const getException = async (id) => {
  const response = await doormileAxios.get(`/admin/exceptions/${id}`);
  return response.data.data;
};

export const updateExceptionStatus = async (id, status, resolution) => {
  // status: 'Resolved' | 'Closed'.
  const response = await doormileAxios.put(`/admin/exceptions/${id}/status`, { status, resolution });
  return response.data;
};

// ==============================|| Competitive intel ||============================== //

export const getCompetitorBranches = async () => {
  const response = await doormileAxios.get('/admin/competitor-branches');
  return response.data.data;
};

export const createCompetitorBranch = async (data) => {
  const response = await doormileAxios.post('/admin/competitor-branches', data);
  return response.data;
};

export const updateCompetitorBranch = async (id, data) => {
  const response = await doormileAxios.put(`/admin/competitor-branches/${id}`, data);
  return response.data;
};

export const deleteCompetitorBranch = async (id) => {
  const response = await doormileAxios.delete(`/admin/competitor-branches/${id}`);
  return response.data;
};

export const getCarrierPricing = async () => {
  const response = await doormileAxios.get('/admin/carrier-pricing');
  return response.data.data;
};

export const createCarrierPricing = async (data) => {
  const response = await doormileAxios.post('/admin/carrier-pricing', data);
  return response.data;
};

export const updateCarrierPricing = async (id, data) => {
  const response = await doormileAxios.put(`/admin/carrier-pricing/${id}`, data);
  return response.data;
};

export const deleteCarrierPricing = async (id) => {
  const response = await doormileAxios.delete(`/admin/carrier-pricing/${id}`);
  return response.data;
};
