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

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

export type PaymentBatchStatus = 'DRAFT' | 'FINALIZED' | 'CANCELLED';

export interface PaymentBatchResp extends Record<string, unknown> {
  batchId: number;
  settleMonth: string;
  batchName: string;
  status: PaymentBatchStatus;
  statusName: string;
  totalCount: number;
  totalPayable: number;
  finalizedAt?: string;
  createdAt: string;
}

export interface PaymentBatchItemResp extends Record<string, unknown> {
  itemId: number;
  settleId: number;
  agentId: number;
  agentName: string;
  payableAmount: number;
  included: boolean;
  excludeReason?: string;
}

export interface PaymentBatchDetailResp extends PaymentBatchResp {
  items: PaymentBatchItemResp[];
}

export interface PaymentBatchCreateReq {
  settleMonth: string;
  batchName: string;
}

export interface PaymentBatchItemUpdateReq {
  included: boolean;
  excludeReason?: string;
}

export interface PaymentBatchSearchParam {
  settleMonth?: string;
  status?: string;
  pageNum?: number;
  pageSize?: number;
}

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

export const paymentBatchApi = {
  list: (p: PaymentBatchSearchParam) =>
    unwrap<PageResponse<PaymentBatchResp>>(
      api.get('/api/payment-batches', { params: p }),
    ),

  detail: (id: number) =>
    unwrap<PaymentBatchDetailResp>(
      api.get(`/api/payment-batches/${id}`),
    ),

  create: (req: PaymentBatchCreateReq) =>
    unwrap<number>(api.post('/api/payment-batches', req)),

  updateItem: (id: number, itemId: number, req: PaymentBatchItemUpdateReq) =>
    unwrap<void>(api.put(`/api/payment-batches/${id}/items/${itemId}`, req)),

  finalize: (id: number) =>
    unwrap<void>(api.put(`/api/payment-batches/${id}/finalize`)),

  cancel: (id: number) =>
    unwrap<void>(api.put(`/api/payment-batches/${id}/cancel`)),

  export: (id: number) =>
    api.get(`/api/payment-batches/${id}/export`, { responseType: 'blob' }),
};
