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

// ── 단계마감 (StepClose) ─────────────────────────────
export interface StepCloseRow extends Record<string, unknown> {
  stepCloseId: number;
  settleMonth: string;
  stepCode: string;
  stepSeq: number;
  status: string;
  closedAt?: string;
  closedBy?: number;
  createdAt?: string;
}

// ── 본사정산 (HqSettle) ──────────────────────────────
export interface HqSettleRow extends Record<string, unknown> {
  itemId: number;
  settleMonth: string;
  itemType: string;
  itemName: string;
  amount: number;
  memo?: string;
  status: string;
  createdAt?: string;
}

export interface HqSettleSummary {
  incomeTotal: number;
  expenseTotal: number;
  profitLoss: number;
}

// ── 등급평가 (GradeEvaluation) ───────────────────────
export interface GradeEvalRuleRow extends Record<string, unknown> {
  ruleId: number;
  gradeId: number;
  gradeName?: string;
  minScore: number;
  effectiveFrom: string;
  effectiveTo?: string;
}

export interface GradeEvalRow extends Record<string, unknown> {
  evalId: number;
  agentId: number;
  agentName?: string;
  evalPeriod: string;
  performanceScore: number;
  prevGradeId?: number;
  prevGradeName?: string;
  evaluatedGradeId?: number;
  evaluatedGradeName?: string;
  status: string;
}

// ── 공동계약 (JointContract) ─────────────────────────
export interface JointContractRow extends Record<string, unknown> {
  jointId: number;
  contractId: number;
  contractNo?: string;
  agentId: number;
  agentName?: string;
  role: string;
  shareRate: number;
  createdAt?: string;
}

// ── 보증보험 (GuaranteeInsurance) ────────────────────
export interface GuaranteeInsuranceRow extends Record<string, unknown> {
  guaranteeId: number;
  agentId: number;
  agentName?: string;
  policyNo: string;
  carrierId?: number;
  carrierName?: string;
  guaranteeAmount: number;
  startDate: string;
  endDate: string;
  status: string;
}

// ── 적립금 (ReserveFund) ─────────────────────────────
export interface ReserveFundRow extends Record<string, unknown> {
  reserveId: number;
  agentId: number;
  agentName?: string;
  settleMonth: string;
  reserveIn: number;
  reserveOut: number;
  balance: number;
  createdAt?: string;
}

// ── 수수료 시뮬레이터 (CommissionSimulation) ──────────
export interface SimulationRow extends Record<string, unknown> {
  simId: number;
  simName: string;
  premiumAmount: number;
  companyRate: number;
  payoutRate: number;
  commissionYear: number;
  companyPayment: number;
  agentCommission: number;
  withholdingTax: number;
  netAmount: number;
  expectedChargeback?: number;
  createdAt?: string;
}

export interface SimulationRequest {
  simName: string;
  premiumAmount: number;
  companyRate: number;
  payoutRate: number;
  commissionYear: number;
}

// ── API ───────────────────────────────────────────────
export const operationApi = {
  // StepClose
  stepCloseList: (params?: { settleMonth?: string }) =>
    unwrap<PageResponse<StepCloseRow>>(
      api.get('/api/step-closes', { params }),
    ),
  stepCloseByMonth: (settleMonth: string) =>
    unwrap<StepCloseRow[]>(
      api.get('/api/step-closes/by-month', { params: { settleMonth } }),
    ),
  stepCloseGet: (id: number) =>
    unwrap<StepCloseRow>(api.get(`/api/step-closes/${id}`)),
  stepCloseCreate: (body: Partial<StepCloseRow>) =>
    unwrap<StepCloseRow>(api.post('/api/step-closes', body)),
  stepCloseClose: (id: number) =>
    unwrap<StepCloseRow>(api.post(`/api/step-closes/${id}/close`)),
  stepCloseReopen: (id: number) =>
    unwrap<StepCloseRow>(api.post(`/api/step-closes/${id}/reopen`)),

  // HqSettle
  hqSettleList: (params?: { settleMonth?: string }) =>
    unwrap<PageResponse<HqSettleRow>>(
      api.get('/api/hq-settles', { params }),
    ),
  hqSettleSummary: (settleMonth: string) =>
    unwrap<HqSettleSummary>(
      api.get('/api/hq-settles/summary', { params: { settleMonth } }),
    ),
  hqSettleGet: (id: number) =>
    unwrap<HqSettleRow>(api.get(`/api/hq-settles/${id}`)),
  hqSettleCreate: (body: Partial<HqSettleRow>) =>
    unwrap<HqSettleRow>(api.post('/api/hq-settles', body)),
  hqSettleUpdate: (id: number, body: Partial<HqSettleRow>) =>
    unwrap<HqSettleRow>(api.put(`/api/hq-settles/${id}`, body)),
  hqSettleDelete: (id: number) =>
    unwrap<void>(api.delete(`/api/hq-settles/${id}`)),

  // GradeEval Rules — 백엔드는 PageResponse({list}) 반환이므로 .list 추출
  gradeEvalRules: () =>
    unwrap<{ list: GradeEvalRuleRow[] }>(api.get('/api/grade-evaluations/rules')).then((r) => r.list ?? []),
  gradeEvalRuleGet: (id: number) =>
    unwrap<GradeEvalRuleRow>(api.get(`/api/grade-evaluations/rules/${id}`)),
  gradeEvalRuleCreate: (body: Partial<GradeEvalRuleRow>) =>
    unwrap<GradeEvalRuleRow>(api.post('/api/grade-evaluations/rules', body)),
  gradeEvalRuleUpdate: (id: number, body: Partial<GradeEvalRuleRow>) =>
    unwrap<GradeEvalRuleRow>(api.put(`/api/grade-evaluations/rules/${id}`, body)),
  gradeEvalRuleDelete: (id: number) =>
    unwrap<void>(api.delete(`/api/grade-evaluations/rules/${id}`)),

  // GradeEval Evaluations
  gradeEvalList: (params?: { agentName?: string; evalPeriod?: string }) =>
    unwrap<PageResponse<GradeEvalRow>>(
      api.get('/api/grade-evaluations', { params }),
    ),
  gradeEvalGet: (evalId: number) =>
    unwrap<GradeEvalRow>(api.get(`/api/grade-evaluations/${evalId}`)),
  gradeEvalCreate: (body: Partial<GradeEvalRow>) =>
    unwrap<GradeEvalRow>(api.post('/api/grade-evaluations', body)),
  gradeEvalApply: (evalId: number) =>
    unwrap<GradeEvalRow>(api.post(`/api/grade-evaluations/${evalId}/apply`)),
  gradeEvalDelete: (evalId: number) =>
    unwrap<void>(api.delete(`/api/grade-evaluations/${evalId}`)),

  // JointContract
  jointContractList: (params?: { contractNo?: string; agentName?: string }) =>
    unwrap<PageResponse<JointContractRow>>(
      api.get('/api/joint-contracts', { params }),
    ),
  jointContractGet: (id: number) =>
    unwrap<JointContractRow>(api.get(`/api/joint-contracts/${id}`)),
  jointContractCreate: (body: Partial<JointContractRow>) =>
    unwrap<JointContractRow>(api.post('/api/joint-contracts', body)),
  jointContractUpdate: (id: number, body: Partial<JointContractRow>) =>
    unwrap<JointContractRow>(api.put(`/api/joint-contracts/${id}`, body)),
  jointContractDelete: (id: number) =>
    unwrap<void>(api.delete(`/api/joint-contracts/${id}`)),

  // GuaranteeInsurance
  guaranteeInsuranceList: (params?: { agentName?: string; status?: string }) =>
    unwrap<PageResponse<GuaranteeInsuranceRow>>(
      api.get('/api/guarantee-insurances', { params }),
    ),
  guaranteeInsuranceGet: (id: number) =>
    unwrap<GuaranteeInsuranceRow>(api.get(`/api/guarantee-insurances/${id}`)),
  guaranteeInsuranceCreate: (body: Partial<GuaranteeInsuranceRow>) =>
    unwrap<GuaranteeInsuranceRow>(api.post('/api/guarantee-insurances', body)),
  guaranteeInsuranceUpdate: (id: number, body: Partial<GuaranteeInsuranceRow>) =>
    unwrap<GuaranteeInsuranceRow>(api.put(`/api/guarantee-insurances/${id}`, body)),
  guaranteeInsuranceDelete: (id: number) =>
    unwrap<void>(api.delete(`/api/guarantee-insurances/${id}`)),

  // ReserveFund
  reserveFundList: (params?: { settleMonth?: string; agentName?: string }) =>
    unwrap<PageResponse<ReserveFundRow>>(
      api.get('/api/reserve-funds', { params }),
    ),
  reserveFundGet: (id: number) =>
    unwrap<ReserveFundRow>(api.get(`/api/reserve-funds/${id}`)),
  reserveFundUpsert: (body: Partial<ReserveFundRow>) =>
    unwrap<ReserveFundRow>(api.post('/api/reserve-funds', body)),

  // CommissionSimulation
  simulationList: (params?: Record<string, unknown>) =>
    unwrap<PageResponse<SimulationRow>>(
      api.get('/api/commission-simulations', { params }),
    ),
  simulationGet: (id: number) =>
    unwrap<SimulationRow>(api.get(`/api/commission-simulations/${id}`)),
  simulate: (body: SimulationRequest) =>
    unwrap<SimulationRow>(api.post('/api/commission-simulations/simulate', body)),
};
