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

// ────────────────────────────────────────────────
// 공통 검색 파라미터
// ────────────────────────────────────────────────

export interface KpiSearchParam {
  fromMonth?: string;    // YYYYMM
  toMonth?: string;      // YYYYMM
  orgId?: number;
  agentId?: number;
  carrierId?: number;
  levelType?: 'AGENT' | 'ORG';
  pageNum?: number;
  pageSize?: number;
}

// ────────────────────────────────────────────────
// 응답 타입
// ────────────────────────────────────────────────

export interface MonthlySummaryRow extends Record<string, unknown> {
  yyyymm: string;
  agentCount: number;
  totalRecruit: number;
  totalMaintain: number;
  totalOverride: number;
  totalChargeback: number;
  totalGross: number;
  totalTax: number;
  totalNet: number;
  totalIncentive: number;
  refreshedAt?: string;
}

export interface OrgSummaryRow extends Record<string, unknown> {
  orgId: number;
  orgName: string;
  orgType?: string;
  yyyymm: string;
  agentCount: number;
  totalRecruit: number;
  totalMaintain: number;
  totalGross: number;
  totalNet: number;
  refreshedAt?: string;
}

export interface RetentionRow extends Record<string, unknown> {
  contractMonth: string;
  carrierId?: number;
  carrierName?: string;
  totalContracts: number;
  retained13m: number;
  retained25m: number;
  retentionRate13m: number;
  retentionRate25m: number;
  refreshedAt?: string;
}

export interface CumulativeRow extends Record<string, unknown> {
  levelType: 'AGENT' | 'ORG';
  entityId: number;
  entityName: string;
  orgId?: number;
  orgName?: string;
  firstSettleMonth?: string;
  lastSettleMonth?: string;
  settleMonthCount: number;
  cumGross: number;
  cumNet: number;
  cumChargeback: number;
  cumOverride: number;
  cumIncentive: number;
  refreshedAt?: string;
}

// ────────────────────────────────────────────────
// API 함수
// ────────────────────────────────────────────────

export const kpiApi = {
  monthlySummary: (p: KpiSearchParam) =>
    unwrap<PageResponse<MonthlySummaryRow>>(
      api.get('/api/kpi/monthly-summary', { params: p }),
    ),

  orgSummary: (p: KpiSearchParam) =>
    unwrap<PageResponse<OrgSummaryRow>>(
      api.get('/api/kpi/org-summary', { params: p }),
    ),

  retention: (p: KpiSearchParam) =>
    unwrap<PageResponse<RetentionRow>>(
      api.get('/api/kpi/retention', { params: p }),
    ),

  cumulative: (p: KpiSearchParam) =>
    unwrap<PageResponse<CumulativeRow>>(
      api.get('/api/kpi/cumulative', { params: p }),
    ),
};
