import recordAxiosInstance from "@/shared/services/recordAxiosInstance";
import { withHeaders } from "./withHeaders";
import {
  RecordPeriodTotals,
  SectorRecordReport,
  SectorReportFilters,
  SectorReportResponse,
} from "@/record-management/components/sectorReports/types";

const numberValue = (value: unknown) => {
  const parsed = Number(value);
  return Number.isFinite(parsed) ? parsed : 0;
};

const normalizeTotals = (value: any): RecordPeriodTotals => ({
  today: numberValue(value?.today),
  thisWeek: numberValue(value?.thisWeek ?? value?.week),
  thisMonth: numberValue(value?.thisMonth ?? value?.month),
  allTime: numberValue(value?.allTime ?? value?.total),
});

const normalizeReport = (item: any): SectorRecordReport => ({
  sectorId: String(item?.sectorId ?? item?.positionId ?? item?.id ?? ""),
  sectorName: item?.sectorName ?? item?.positionName ?? item?.name ?? "—",
  groupId: item?.groupId ?? null,
  groupName: item?.groupName ?? null,
  incoming: normalizeTotals(item?.incoming ?? item?.incomingRecords),
  outgoing: normalizeTotals(item?.outgoing ?? item?.outgoingRecords),
});

/**
 * Sector activity report contract.
 *
 * The normalizer accepts both `{ items: [...] }` and a bare array, and common
 * period aliases, so minor backend response differences remain isolated here.
 */
export const fetchSectorRecordReport = async (
  filters: SectorReportFilters = {},
): Promise<SectorReportResponse> => {
  const { unitId, ...remainingFilters } = filters;
  const isAllSectors = Boolean(unitId && !remainingFilters.positionId);
  const endpoint = isAllSectors
    ? `/reports/sector-records/unit/${encodeURIComponent(unitId!)}`
    : "/reports/sector-records";

  const { data } = await recordAxiosInstance.get(endpoint, {
    params: isAllSectors ? remainingFilters : filters,
    headers: withHeaders(),
  });
  const items = Array.isArray(data) ? data : (data?.items ?? []);
  return { items: items.map(normalizeReport) };
};
