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

// ── Types ──────────────────────────────────────────

export type ClawbackStatus = 'OUTSTANDING' | 'RECOVERING' | 'CLEARED' | 'WRITTEN_OFF';

export interface ClawbackReceivableRow extends Record<string, unknown> {
  receivableId: number;
  agentId: number;
  agentName: string;
  originSettleMonth: string;
  originalAmount: number;
  recoveredAmount: number;
  balance: number;
  status: ClawbackStatus;
  statusName: string;
  lastRecoveryMonth?: string;
  writeoffReason?: string;
  createdAt: string;
}

export interface ClawbackRecoveryItem {
  settleMonth: string;
  recoveredAmount: number;
  createdAt: string;
}

export interface ClawbackReceivableDetail extends ClawbackReceivableRow {
  recoveries: ClawbackRecoveryItem[];
}

export interface ClawbackSummaryRow extends Record<string, unknown> {
  agentId: number;
  agentName: string;
  totalBalance: number;
  receivableCount: number;
}

export interface ClawbackSearchParam {
  agentId?: number;
  agentName?: string;
  status?: string;
  originSettleMonth?: string;
  pageNum?: number;
  pageSize?: number;
}

export interface WriteOffParam {
  status: 'CLEARED' | 'WRITTEN_OFF';
  writeoffReason: string;
}

// ── API ───────────────────────────────────────────

export const clawbackReceivableApi = {
  list: (p: ClawbackSearchParam) =>
    unwrap<PageResponse<ClawbackReceivableRow>>(
      api.get('/api/clawback-receivables', { params: p }),
    ),

  summary: () =>
    unwrap<ClawbackSummaryRow[]>(
      api.get('/api/clawback-receivables/summary'),
    ),

  detail: (id: number) =>
    unwrap<ClawbackReceivableDetail>(
      api.get(`/api/clawback-receivables/${id}`),
    ),

  writeOff: (id: number, body: WriteOffParam) =>
    unwrap<ClawbackReceivableRow>(
      api.put(`/api/clawback-receivables/${id}/write-off`, body),
    ),

  export: (p: ClawbackSearchParam) =>
    api.get('/api/clawback-receivables/export', {
      params: p,
      responseType: 'blob',
    }),
};
