import api, { unwrap } from './request';

export interface BatchRunResp {
  jobLogId: number;
}

export interface BatchJobLogResp {
  jobLogId: number;
  jobName: string;
  status: 'REQUESTED' | 'RUNNING' | 'COMPLETED' | 'FAILED';
  stepName?: string;
  totalCount?: number;
  successCount?: number;
  errorCount?: number;
  startedAt?: string;
  endedAt?: string;
  durationMs?: number;
  errorMessage?: string;
}

export interface BatchHistoryResp {
  jobLogId: number;
  jobName: string;
  status: string;
  stepName?: string;
  startedAt?: string;
  endedAt?: string;
  durationMs?: number;
  errorMessage?: string;
}

/** 백엔드 batch_job_log VO (실제 응답 형태) */
interface BatchJobVO {
  jobId: number;
  jobName: string;
  status: string;            // REQUESTED | STARTED | COMPLETED | FAILED
  currentStep?: string;
  totalCount?: number;
  processedCount?: number;
  errorCount?: number;
  errorMessage?: string;
  startedAt?: number[] | string;
  finishedAt?: number[] | string;
  durationSec?: number;
}

/** LocalDateTime 배열([y,M,d,h,m,s,..]) → 'YYYY-MM-DD HH:mm:ss' */
function fmtTs(v?: number[] | string): string | undefined {
  if (v == null) return undefined;
  if (typeof v === 'string') return v;
  const [y, mo, d, h = 0, mi = 0, s = 0] = v;
  const p = (n: number) => String(n).padStart(2, '0');
  return `${y}-${p(mo)}-${p(d)} ${p(h)}:${p(mi)}:${p(s)}`;
}

function mapStatus(s: string): BatchJobLogResp['status'] {
  if (s === 'STARTED') return 'RUNNING';
  if (s === 'REQUESTED' || s === 'RUNNING' || s === 'COMPLETED' || s === 'FAILED') return s;
  return 'RUNNING';
}

/** 백엔드 VO → 프론트 BatchJobLogResp 어댑터 */
function toJobLog(v: BatchJobVO): BatchJobLogResp {
  return {
    jobLogId: v.jobId,
    jobName: v.jobName,
    status: mapStatus(v.status),
    stepName: v.currentStep,
    totalCount: v.totalCount,
    successCount: v.processedCount,
    errorCount: v.errorCount,
    startedAt: fmtTs(v.startedAt),
    endedAt: fmtTs(v.finishedAt),
    durationMs: v.durationSec != null ? v.durationSec * 1000 : undefined,
    errorMessage: v.errorMessage,
  };
}

export const batchRunApi = {
  run: (settleMonth: string, companyCode?: string) =>
    unwrap<number>(api.post('/api/batch/settlement/run', { settleMonth, companyCode })),
  status: (jobLogId: number) =>
    unwrap<BatchJobVO>(api.get(`/api/batch/jobs/${jobLogId}`)).then(toJobLog),
  history: (size = 10) =>
    unwrap<BatchJobVO[]>(api.get('/api/batch/jobs')).then((rows) =>
      rows.slice(0, size).map(toJobLog) as BatchHistoryResp[],
    ),
};
