// 2026-11-11 — Companies → "🔀 Merge duplicates" (admins only)
import { fetchApi, API_BASE_URL } from "@/lib/api/http";

const BASE = `${API_BASE_URL}/companies/merge/smart`;

export interface SmartCompany {
  id: number;
  name: string;
  company_code: string | null;
  contact_person: string | null;
  email: string | null;
  mobile: string | null;
  city: string | null;
  client_group: string | null;
  created_at: string | null;
  certificates: number;
  active_certificates: number;
  schedules: number;
  schedules_all: number;
  audit_requests: number;
  jobs: number;
  branches: number;
  portal_users: number;
  real: boolean;
}

export type SmartStatus = "clear" | "review" | "no_activity";

export interface SmartGroup {
  key: string;
  label: string;
  status: SmartStatus;
  keeper_id: number;
  reason: string;
  companies: SmartCompany[];
}

export interface SmartTotals {
  groups: number;
  companies: number;
  clear: number;
  review: number;
  no_activity: number;
}

export interface OrphanReport {
  applied: boolean;
  tables: { table: string; orphan_rows: number; fixable: number; fixed: number }[];
}

export const getSmartMergeAccess = () => fetchApi<{ can_merge: boolean }>(`${BASE}/access`);
export const getSmartGroups = () => fetchApi<{ groups: SmartGroup[]; totals: SmartTotals }>(BASE);
export const smartMerge = (groups: { keep_id: number; remove_ids: number[] }[]) =>
  fetchApi<{ merged: number; groups: number; results: { keep_id: number; removed: number[]; failed: { id: number; error: string }[] }[] }>(BASE, {
    method: "POST",
    body: JSON.stringify({ groups }),
  });
export const getOrphans = () => fetchApi<OrphanReport>(`${BASE}/orphans`);
export const fixOrphans = () => fetchApi<OrphanReport>(`${BASE}/orphans`, { method: "POST" });
