import type { AssetStatusReportRow } from '../components/AssetStatusReportModal';

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

export type AssetDeviceStatusSummaryResponse = {
  total_assets: number;
  assets_down: number;
  chart: {
    labels: string[];
    datasets: Array<{ name: string; values: number[]; colors: string[] }>;
    type: 'Pie';
    total: number;
  };
};

export async function fetchAssetsForStatusModal(
  filters: AssetDeviceStatusSummaryFilters
): Promise<AssetStatusReportRow[]> {
  const csrfToken =
    typeof window !== 'undefined' && (window as any).csrf_token && (window as any).csrf_token !== 'None'
      ? (window as any).csrf_token
      : null;

  const headers: Record<string, string> = {
    'Content-Type': 'application/json',
    Accept: 'application/json',
  };
  if (csrfToken) headers['X-Frappe-CSRF-Token'] = csrfToken;

  const listFilters: Array<[string, string, unknown]> = [];

  if (filters.company) listFilters.push(['company', '=', filters.company]);
  if (filters.site_name) listFilters.push(['custom_site', '=', filters.site_name]);
  if (filters.from_date && filters.to_date) {
    listFilters.push(['creation', 'between', [`${filters.from_date} 00:00:00`, `${filters.to_date} 23:59:59`]]);
  } else if (filters.from_date) {
    listFilters.push(['creation', '>=', `${filters.from_date} 00:00:00`]);
  } else if (filters.to_date) {
    listFilters.push(['creation', '<=', `${filters.to_date} 23:59:59`]);
  }

  const response = await fetch('/api/method/frappe.client.get_list', {
    method: 'POST',
    headers,
    credentials: 'include',
    body: JSON.stringify({
      doctype: 'Asset',
      fields: ['name', 'asset_name', 'custom_device_status', 'location', 'department', 'company', 'custom_site'],
      filters: listFilters,
      limit_page_length: 500,
      order_by: 'modified desc',
    }),
  });

  const payload = await response.json();
  if (!response.ok) {
    throw new Error(payload?.message || payload?.exc || 'Failed to load assets');
  }

  const rows = payload?.message || [];
  return Array.isArray(rows) ? rows : [];
}
