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

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

export type ChargebackStatus = 'NEW' | 'PROCESSING' | 'SETTLED' | 'CANCELLED';

export interface ChargebackRow extends Record<string, unknown> {
  cbId: number;
  policyNo: string;
  agentId: number;
  agentName: string;
  contractorName: string;
  lapseMonth: number | null;
  cbRate: number | null;
  cbAmount: number;
  paidAmount: number;
  remainAmount: number;
  settleMonth: string;
  status: ChargebackStatus;
  createdAt: string;
}

export interface ChargebackSearchParam {
  settleMonth?: string;
  agentId?: number;
  status?: string;
  policyNo?: string;
  pageNum?: number;
  pageSize?: number;
}

export interface ChargebackUploadResult {
  successCount: number;
  errorCount: number;
  skipCount: number;
  errors: Array<{ rowNo: number; reason: string }>;
}

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

export const chargebackApi = {
  list: (p: ChargebackSearchParam) =>
    unwrap<PageResponse<ChargebackRow>>(
      api.get('/api/chargebacks', { params: p }),
    ),

  upload: (settleMonth: string, file: File) => {
    const form = new FormData();
    form.append('file', file);
    return unwrap<ChargebackUploadResult>(
      api.post(`/api/chargebacks/upload?settleMonth=${settleMonth}`, form, {
        headers: { 'Content-Type': 'multipart/form-data' },
      }),
    );
  },

  export: (p: ChargebackSearchParam) =>
    api.get('/api/chargebacks/export', {
      params: p,
      responseType: 'blob',
    }),
};
