/** Hospitals that use Mobile Team Site (Site Name) filtering. */
export function isSiteEnabledHospital(company?: string | null): boolean {
  if (!company) return false;
  return company.startsWith('Mobile') || company.startsWith('Dental');
}

export type DashboardLocationFilters = {
  company?: string;
  site_name?: string;
  from_date?: string;
  to_date?: string;
};

/** Filters for dashboard chart/report API (company + site_name + optional dates). */
export function buildDashboardReportFilters(
  hospital?: string,
  siteName?: string,
  fromDate?: string,
  toDate?: string
): DashboardLocationFilters {
  const filters: DashboardLocationFilters = {};
  if (hospital) filters.company = hospital;
  if (siteName && isSiteEnabledHospital(hospital)) filters.site_name = siteName;
  if (fromDate) filters.from_date = fromDate;
  if (toDate) filters.to_date = toDate;
  return filters;
}

/** Work Order list API filters. */
export function buildWorkOrderDashboardFilters(
  hospital?: string,
  siteName?: string
): Record<string, string> {
  const filters: Record<string, string> = {};
  if (hospital) filters.company = hospital;
  if (siteName && isSiteEnabledHospital(hospital)) filters.site_name = siteName;
  return filters;
}

/** Asset Maintenance Log list API filters. */
export function buildMaintenanceLogDashboardFilters(
  hospital?: string,
  siteName?: string
): Record<string, string> {
  const filters: Record<string, string> = {};
  if (hospital) filters.custom_hospital_name = hospital;
  if (siteName && isSiteEnabledHospital(hospital)) filters.site_name = siteName;
  return filters;
}

/** Frappe REST Asset resource filter tuples. */
export function buildAssetResourceFilters(
  hospital?: string,
  siteName?: string
): [string, string, string][] {
  const filters: [string, string, string][] = [];
  if (hospital) filters.push(['company', '=', hospital]);
  if (siteName && isSiteEnabledHospital(hospital)) {
    filters.push(['custom_site', '=', siteName]);
  }
  return filters;
}

/** LinkField filters for Mobile Team Site (Asset custom_site / Work Order site_name). */
export function buildMobileTeamSiteFilters(
  company?: string | null,
  userPhccSiteName?: string | null
): Record<string, string> {
  const filters: Record<string, string> = {};

  if (company && isSiteEnabledHospital(company)) {
    filters.mobile_team = company;
  }

  if (userPhccSiteName) {
    filters.name = userPhccSiteName;
  }

  return filters;
}

/** LinkField filters for Company/Hospital based on user permissions. */
export function buildHospitalLinkFilters(
  allowedHospitals?: string[]
): Record<string, unknown> {
  const filters: Record<string, unknown> = { domain: 'Healthcare' };

  if (allowedHospitals?.length) {
    filters.name = ['in', allowedHospitals];
  }

  return filters;
}
