// ERP 마스터 동기화 API 클라이언트
// 자동화 관리 > 배치 관리 화면의 "ERP 동기화" 탭에서 호출

import { apiClient } from "./client";

export interface ErpSyncResult {
  resource: string;
  fetched: number;
  inserted: number;
  updated: number;
  skipped: number;
  errors: string[];
  durationMs: number;
}

export type ErpSyncResource =
  | "employees"
  | "departments"
  | "warehouses"
  | "customers"
  | "account-codes"
  | "all";

interface ErpSyncRequest {
  coCd: string;
  companyCode?: string;
  searchText?: string;
  baselocFg?: string;
}

interface SingleResponse {
  success: boolean;
  data?: ErpSyncResult;
  message?: string;
}

interface AllResponse {
  success: boolean;
  totals?: {
    fetched: number;
    inserted: number;
    updated: number;
    skipped: number;
    errorsCount: number;
  };
  data?: ErpSyncResult[];
  message?: string;
}

const BASE = "/erp-sync";

export const ErpSyncAPI = {
  async syncOne(resource: Exclude<ErpSyncResource, "all">, body: ErpSyncRequest): Promise<ErpSyncResult> {
    const res = await apiClient.post<SingleResponse>(`${BASE}/${resource}`, body);
    if (!res.data.success) {
      throw new Error(res.data.message || `${resource} 동기화 실패`);
    }
    return res.data.data!;
  },

  async syncAll(body: ErpSyncRequest): Promise<{ totals: AllResponse["totals"]; results: ErpSyncResult[] }> {
    const res = await apiClient.post<AllResponse>(`${BASE}/all`, body);
    return {
      totals: res.data.totals,
      results: res.data.data || [],
    };
  },
};
