'use client';

import type {
  HostDetail,
  HostStats,
  HostSummary,
  RotatePushSecretResponse,
  RotateCallbackSecretResponse,
  RotateSecretResponse,
  UpdateHostRequest,
} from '@pac/types';
import { api } from '@/lib/api-client';

const BASE = '/pac/v1/admin/host/self';

export interface ColdImportTotals {
  patientsUpserted: number;
  transactionsWritten: number;
  duplicates: number;
  failed: number;
  factsCreated: number;
  factsSuperseded: number;
  factsUnchanged: number;
  factsEvidenceAppended: number;
  factsFailed: number;
}

export interface ColdImportStatus {
  /** BullMQ job 状态:waiting/active/completed/failed/...;'not_found' = 已清理或不存在 */
  state: string;
  /** 完成时的 ImportRunResult(含 totals + dryRun 标志);进行中为 null */
  result: { status?: string; dryRun?: boolean; totals?: ColdImportTotals } | null;
  failedReason: string | null;
  /** 运行中的真实进度(cohortDone/cohortTotal 批次);非运行态或 dryRun 为 null */
  progress: { done: number; total: number } | null;
}

export const hostApi = {
  getSelf: () => api.get<HostDetail>(BASE),
  getStats: () => api.get<HostStats>(`${BASE}/stats`),
  update: (body: UpdateHostRequest) => api.patch<HostSummary>(BASE, body),

  rotateAppSecret: () => api.post<RotateSecretResponse>(`${BASE}/rotate-app-secret`),
  addPushSecret: () => api.post<RotatePushSecretResponse>(`${BASE}/push-secrets`),
  removePushSecret: (suffix: string) =>
    api.delete<{ totalKeysRemaining: number }>(`${BASE}/push-secrets/${encodeURIComponent(suffix)}`),

  addCallbackSecret: () => api.post<RotateCallbackSecretResponse>(`${BASE}/callback-secrets`),
  removeCallbackSecret: (suffix: string) =>
    api.delete<{ totalKeysRemaining: number }>(
      `${BASE}/callback-secrets/${encodeURIComponent(suffix)}`,
    ),

  // 数据导入:上传压缩包(FormData 字段名 file)→ 返回 jobId;按 jobId 轮询进度
  importArchive: (form: FormData) => api.post<{ jobId: string }>(`${BASE}/cold-import`, form),
  getImportStatus: (jobId: string) =>
    api.get<ColdImportStatus>(`${BASE}/cold-import/${encodeURIComponent(jobId)}`),
};
