import API_CONFIG from '../config/api';
import apiService from './apiService';
import { formatFrappeApiError } from '../utils/frappeErrorMessage';

export type WoFeedbackReportFilters = {
  work_order?: string;
  requester_name?: string;
  rating?: string;
  company?: string;
  site_name?: string;
};

export type WoFeedbackReportColumn = {
  label?: string;
  fieldname: string;
  fieldtype?: string;
  options?: string;
  width?: number;
};

export type WoFeedbackReportResponse = {
  columns?: WoFeedbackReportColumn[];
  result?: Record<string, unknown>[];
};

export type WoFeedbackSummaryChartResponse = {
  labels?: string[];
  datasets?: Array<{ name?: string; values?: number[]; colors?: string[] }>;
  type?: string;
};

async function callMethod<T>(method: string, args: Record<string, unknown> = {}): Promise<T> {
  const csrf = (await apiService.getCSRFToken()) || (await apiService.getCSRFTokenForGuest());
  const headers: Record<string, string> = {
    Accept: 'application/json',
    'Content-Type': 'application/json',
  };
  if (csrf) headers['X-Frappe-CSRF-Token'] = csrf;

  const res = await fetch(`${API_CONFIG.BASE_URL}/api/method/${method}`, {
    method: 'POST',
    credentials: 'include',
    headers,
    body: JSON.stringify(args),
  });

  const body = await res.json().catch(() => ({}));
  if (!res.ok || body.exc) {
    throw new Error(formatFrappeApiError(body) || body?.message || `HTTP ${res.status}`);
  }

  return body.message as T;
}

function cleanFilters(filters: WoFeedbackReportFilters): Record<string, string> {
  const cleaned: Record<string, string> = {};
  Object.entries(filters).forEach(([key, value]) => {
    if (value) cleaned[key] = value;
  });
  return cleaned;
}

export async function runWoFeedbackReport(
  filters: WoFeedbackReportFilters = {}
): Promise<WoFeedbackReportResponse> {
  return callMethod<WoFeedbackReportResponse>(
    'asset_lite.api.wo_feedback_api.run_wo_feedback_report',
    { filters: cleanFilters(filters) }
  );
}

export async function fetchWoFeedbackSummary(
  filters: WoFeedbackReportFilters = {}
): Promise<WoFeedbackSummaryChartResponse> {
  return callMethod<WoFeedbackSummaryChartResponse>(
    'asset_lite.api.wo_feedback_api.get_wo_feedback_summary',
    { filters: cleanFilters(filters) }
  );
}

const woFeedbackReportService = {
  runWoFeedbackReport,
  fetchWoFeedbackSummary,
};

export default woFeedbackReportService;
