import { apiClient } from '@/lib/api-client';
import type {
  CrmReportCatalogResponse,
  CrmReportFiltersResponse,
  CrmReportsResponse,
  CrmSharedReportFilters,
  CrmPipelineReportResponse,
  CrmLeadAgingReportResponse,
  CrmOpportunityAgingReportResponse
} from './types';

function buildReportQuery(filters: CrmSharedReportFilters) {
  const searchParams = new URLSearchParams();

  if (filters.dateFrom) searchParams.set('dateFrom', filters.dateFrom);
  if (filters.dateTo) searchParams.set('dateTo', filters.dateTo);
  if (filters.branch) searchParams.set('branch', filters.branch);
  if (filters.productType) searchParams.set('productType', filters.productType);
  if (filters.sales) searchParams.set('sales', filters.sales);
  if (filters.customer) searchParams.set('customer', filters.customer);
  if (filters.customerOwner) searchParams.set('customerOwner', filters.customerOwner);
  if (filters.leadSource) searchParams.set('leadSource', filters.leadSource);
  if (filters.pipelineStage) searchParams.set('pipelineStage', filters.pipelineStage);
  if (filters.outcome) searchParams.set('outcome', filters.outcome);
  if (filters.lostReason) searchParams.set('lostReason', filters.lostReason);

  return searchParams.toString();
}

export async function getCrmReports() {
  return apiClient<CrmReportsResponse>('/crm/reports');
}

export async function getCrmReportCatalog() {
  return apiClient<CrmReportCatalogResponse>('/crm/reports/catalog');
}

export async function getCrmReportFilters() {
  return apiClient<CrmReportFiltersResponse>('/crm/reports/filters');
}

export async function getCrmPipelineReport(filters: CrmSharedReportFilters) {
  const query = buildReportQuery(filters);
  return apiClient<CrmPipelineReportResponse>(`/crm/reports/pipeline${query ? `?${query}` : ''}`);
}

export async function getCrmLeadAgingReport(filters: CrmSharedReportFilters) {
  const query = buildReportQuery(filters);
  return apiClient<CrmLeadAgingReportResponse>(
    `/crm/reports/lead-aging${query ? `?${query}` : ''}`
  );
}

export async function getCrmOpportunityAgingReport(filters: CrmSharedReportFilters) {
  const query = buildReportQuery(filters);
  return apiClient<CrmOpportunityAgingReportResponse>(
    `/crm/reports/opportunity-aging${query ? `?${query}` : ''}`
  );
}

