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

export interface WithdrawResp extends Record<string, unknown> {
  requestId: number;
  settleMasterId?: number;
  settleMonth?: string;
  agentId: number;
  agentName?: string;
  amount: number;
  bankCode?: string;
  accountNo?: string;
  status: string;
  statusName?: string;
  requestedAt?: string;
  sentAt?: string;
  completedAt?: string;
  failReason?: string;
  transferTxId?: string;
  transferStatus?: string;
}

export interface WithdrawSearchParam {
  settleMasterId?: number;
  pageNum?: number;
  pageSize?: number;
}

export interface SettleMasterResp {
  settleId: number;
  settleMonth: string;
  netAmount?: number;
  grossAmount?: number;
  status?: string;
  statusName?: string;
}

export interface WithdrawCreateReq {
  settleMasterId: number;
  amount: number;
  bankCode: string;
  accountNo: string;
}

export interface WithdrawableBalance {
  settleId: number;
  netAmount: number;
  usedAmount: number;
  remainingAmount: number;
}

export const withdrawApi = {
  /** 본인 출금 신청 이력 — 서버측이 토큰 → agentId 강제 필터. */
  list: (params: WithdrawSearchParam = {}) =>
    unwrap<PageResponse<WithdrawResp>>(api.get('/api/mobile/me/withdraw-requests', { params })),

  /** 출금 신청 가능 정산 마스터 (본인 agentId 기준). */
  settleMasters: () =>
    unwrap<SettleMasterResp[]>(api.get('/api/mobile/me/settle-masters')),

  /** 선택한 정산 마스터의 출금 가능 잔액 (net - 활성 출금합계). */
  withdrawableBalance: (settleMasterId: number) =>
    unwrap<WithdrawableBalance>(
      api.get(`/api/mobile/me/settle-masters/${settleMasterId}/withdrawable-balance`),
    ),

  /** 본인 출금 신청 등록. */
  create: (req: WithdrawCreateReq) =>
    unwrap<number>(api.post('/api/mobile/me/withdraw-requests', req)),

  /** 본인 출금 신청 취소 (REQUESTED 상태만). */
  cancel: (requestId: number) =>
    unwrap<void>(api.post(`/api/mobile/me/withdraw-requests/${requestId}/cancel`)),
};
