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

export interface SettleResp {
  settleId: number;
  agentId: number;
  agentName: string;
  orgName?: string;
  gradeName?: string;
  settleMonth: string;
  recruitTotal?: number;
  maintainTotal?: number;
  exceptionPlus?: number;
  exceptionMinus?: number;
  overrideTotal?: number;
  chargebackTotal?: number;
  grossAmount?: number;
  taxAmount?: number;
  netAmount?: number;
  status: string;
  statusName?: string;
  holdReason?: string;
}

export interface SettleSearchParam {
  pageNum?: number;
  pageSize?: number;
  settleMonth?: string;
  agentId?: number;
  orgId?: number;
  status?: string;
}

export const settleApi = {
  list: (p: SettleSearchParam) =>
    unwrap<PageResponse<SettleResp>>(api.get('/api/settle', { params: p })),
  summary: (settleMonth: string) =>
    unwrap<Record<string, number>>(api.get('/api/settle/summary', { params: { settleMonth } })),
  orgSummary: (settleMonth: string) =>
    unwrap<Array<Record<string, unknown>>>(api.get('/api/settle/org-summary', { params: { settleMonth } })),
  confirm: (settleId: number) =>
    unwrap<void>(api.put(`/api/settle/${settleId}/confirm`)),
  hold: (settleId: number, reason: string) =>
    unwrap<void>(api.put(`/api/settle/${settleId}/hold`, { reason })),
  release: (settleId: number) =>
    unwrap<void>(api.put(`/api/settle/${settleId}/release`)),
};

export interface BatchJobLog {
  jobId: number;
  jobName: string;
  settleMonth?: string;
  status: string;
  currentStep?: string;
  progressPct?: number;
  errorMessage?: string;
  startedAt?: string;
  finishedAt?: string;
  durationSec?: number;
}

export const batchApi = {
  run: (settleMonth: string) =>
    unwrap<number>(api.post('/api/batch/settlement/run', { settleMonth })),
  status: () =>
    unwrap<BatchJobLog>(api.get('/api/batch/status')),
};
