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

// ── 공통 ──────────────────────────────────────────
export interface CommissionSearchParam {
  agentId?: number;
  agentName?: string;
  settleMonth?: string;   // YYYYMM
  commissionType?: string;
  pageNum?: number;
  pageSize?: number;
}

// ── CommissionMaster ──────────────────────────────
export interface CommissionMasterRow extends Record<string, unknown> {
  masterId: number;
  agentId: number;
  agentName: string;
  settleMonth: string;
  commissionType: string;
  commissionTypeName: string;
  grossAmount: number;
  netAmount: number;
  status: string;
}

// ── CollectionCommission ──────────────────────────
export interface CollectionRuleRow extends Record<string, unknown> {
  ruleId: number;
  carrierId: number;
  carrierName: string;
  productType: string;
  paymentCycle: string;
  ratePercent: number;
  effectiveFrom: string;
  effectiveTo?: string;
  status: string;
}

export interface CollectionLedgerRow extends Record<string, unknown> {
  ledgerId: number;
  agentId: number;
  agentName: string;
  contractNo: string;
  settleMonth: string;
  collectionAmount: number;
  commissionAmount: number;
  ratePercent: number;
  status: string;
}

// ── RenewalCommission ─────────────────────────────
export interface RenewalRuleRow extends Record<string, unknown> {
  ruleId: number;
  carrierId: number;
  carrierName: string;
  productType: string;
  ratePercent: number;
  effectiveFrom: string;
  effectiveTo?: string;
  status: string;
}

export interface RenewalLedgerRow extends Record<string, unknown> {
  ledgerId: number;
  agentId: number;
  agentName: string;
  contractNo: string;
  settleMonth: string;
  renewalPremium: number;
  commissionAmount: number;
  status: string;
}

// ── ReinstatementCommission ───────────────────────
export interface ReinstatementRuleRow extends Record<string, unknown> {
  ruleId: number;
  carrierId: number;
  carrierName: string;
  productType: string;
  ratePercent: number;
  effectiveFrom: string;
  effectiveTo?: string;
  status: string;
}

export interface ReinstatementLedgerRow extends Record<string, unknown> {
  ledgerId: number;
  agentId: number;
  agentName: string;
  contractNo: string;
  settleMonth: string;
  reinstatementPremium: number;
  commissionAmount: number;
  status: string;
}

// ── PersistencyBonus ──────────────────────────────
export interface PersistencyRuleRow extends Record<string, unknown> {
  ruleId: number;
  bonusType: string;   // 13M/25M/37M/49M
  minRate: number;
  bonusAmount?: number;
  bonusRate?: number;
  effectiveFrom: string;
  effectiveTo?: string;
  status: string;
}

export interface PersistencyBonusRow extends Record<string, unknown> {
  bonusId: number;
  agentId: number;
  agentName: string;
  bonusType: string;
  evaluationMonth: string;
  retentionRate: number;
  bonusAmount: number;
  paidYn: string;
  status: string;
}

// ── OverrideLedger ────────────────────────────────
export interface OverrideLedgerRow extends Record<string, unknown> {
  ledgerId: number;
  fromAgentId: number;
  fromAgentName: string;
  toAgentId: number;
  toAgentName: string;
  settleMonth: string;
  baseCommission: number;
  overrideRate: number;
  overrideAmount: number;
  orgId: number;
  orgName: string;
  status: string;
}

export interface OverrideLedgerSearchParam {
  fromAgentId?: number;
  toAgentId?: number;
  agentName?: string;
  settleMonth?: string;
  orgId?: number;
  pageNum?: number;
  pageSize?: number;
}

// ── P7: IncomeCommission ──────────────────────────
export interface IncomeLedgerRow extends Record<string, unknown> {
  incomeId: number;
  contractId: number;
  contractNo: string;
  carrierId: number;
  carrierName: string;
  settleMonth: string;
  premiumAmount: number;
  companyRate: number;
  incomeAmount: number;
  commissionType: string;
  status: string;
}

export interface MarginSummaryRow extends Record<string, unknown> {
  marginId: number;
  settleMonth: string;
  agentId?: number;
  agentName?: string;
  incomeTotal: number;
  payoutTotal: number;
  marginAmount: number;
  marginRate?: number;
}

// ── P7: ReferralCommission ────────────────────────
export interface ReferralRuleRow extends Record<string, unknown> {
  ruleId: number;
  referralType: string;
  calcType: string;
  commissionRate?: number;
  fixedAmount?: number;
  effectiveFrom: string;
  effectiveTo?: string;
}

export interface ReferralLedgerRow extends Record<string, unknown> {
  ledgerId: number;
  contractId: number;
  contractNo: string;
  referrerAgentId: number;
  referrerAgentName: string;
  settleMonth: string;
  referralType: string;
  baseAmount: number;
  commissionRate?: number;
  commissionAmount: number;
  status: string;
}

// ── P7: SettlingSupport ───────────────────────────
export interface SettlingSupportRuleRow extends Record<string, unknown> {
  ruleId: number;
  agentGrade: string;
  supportAmount: number;
  durationMonths: number;
  clawbackMonths: number;
  effectiveFrom: string;
  effectiveTo?: string;
}

export interface SettlingSupportLedgerRow extends Record<string, unknown> {
  ledgerId: number;
  agentId: number;
  agentName: string;
  settleMonth: string;
  supportAmount: number;
  clawbackAmount: number;
  netAmount: number;
  status: string;
}

// ── P7: RecognizedPerformance ─────────────────────
export interface ConversionRateRow extends Record<string, unknown> {
  rateId: number;
  productId: number;
  productName: string;
  conversionRate: number;
  effectiveFrom: string;
  effectiveTo?: string;
}

export interface RecognizedLedgerRow extends Record<string, unknown> {
  ledgerId: number;
  agentId: number;
  agentName: string;
  contractId: number;
  contractNo: string;
  settleMonth: string;
  premiumAmount: number;
  conversionRate: number;
  convertedPremium: number;
  recognitionRate: number;
  recognizedAmount: number;
  status: string;
}

// ── P7: Award ─────────────────────────────────────
export interface AwardRuleRow extends Record<string, unknown> {
  ruleId: number;
  awardType: string;
  calcType: string;
  thresholdAmount?: number;
  awardRate?: number;
  awardFixed?: number;
  effectiveFrom: string;
  effectiveTo?: string;
}

export interface AwardLedgerRow extends Record<string, unknown> {
  ledgerId: number;
  agentId: number;
  agentName: string;
  settleMonth: string;
  awardType: string;
  baseAmount: number;
  awardAmount: number;
  status: string;
}

// ── P7: LifeSupport ───────────────────────────────
export interface LifeSupportRuleRow extends Record<string, unknown> {
  ruleId: number;
  agentGrade: string;
  supportRate: number;
  effectiveFrom: string;
  effectiveTo?: string;
}

export interface LifeSupportLedgerRow extends Record<string, unknown> {
  ledgerId: number;
  agentId: number;
  agentName: string;
  settleMonth: string;
  baseAmount: number;
  supportRate: number;
  supportAmount: number;
  clawbackAmount: number;
  netAmount: number;
  status: string;
}

// ── P7: BranchAllowance ───────────────────────────
export interface BranchAllowanceRuleRow extends Record<string, unknown> {
  ruleId: number;
  positionCode: string;
  allowanceRate: number;
  capAmount?: number;
  effectiveFrom: string;
  effectiveTo?: string;
}

export interface BranchAllowanceLedgerRow extends Record<string, unknown> {
  ledgerId: number;
  managerAgentId: number;
  managerAgentName: string;
  orgId: number;
  orgName: string;
  settleMonth: string;
  baseAmount: number;
  allowanceRate: number;
  allowanceAmount: number;
  clawbackAmount: number;
  status: string;
}

// ── API ───────────────────────────────────────────
export const commissionApi = {
  // CommissionMaster
  masterList: (p: CommissionSearchParam) =>
    unwrap<PageResponse<CommissionMasterRow>>(
      api.get('/api/commissions', { params: p }),
    ),
  masterByAgent: (agentId: number, yyyymm: string) =>
    unwrap<CommissionMasterRow[]>(
      api.get(`/api/commissions/agent/${agentId}`, { params: { yyyymm } }),
    ),

  // CollectionCommission
  collectionRules: (p?: Partial<CommissionSearchParam>) =>
    unwrap<PageResponse<CollectionRuleRow>>(
      api.get('/api/collection-commissions/rules', { params: p }),
    ),
  collectionRuleCreate: (body: Partial<CollectionRuleRow>) =>
    unwrap<CollectionRuleRow>(api.post('/api/collection-commissions/rules', body)),
  collectionRuleUpdate: (id: number, body: Partial<CollectionRuleRow>) =>
    unwrap<CollectionRuleRow>(api.put(`/api/collection-commissions/rules/${id}`, body)),
  collectionRuleDelete: (id: number) =>
    unwrap<void>(api.delete(`/api/collection-commissions/rules/${id}`)),
  collectionLedgers: (p: CommissionSearchParam) =>
    unwrap<PageResponse<CollectionLedgerRow>>(
      api.get('/api/collection-commissions/ledgers', { params: p }),
    ),

  // RenewalCommission
  renewalRules: (p?: Partial<CommissionSearchParam>) =>
    unwrap<PageResponse<RenewalRuleRow>>(
      api.get('/api/renewal-commissions/rules', { params: p }),
    ),
  renewalRuleCreate: (body: Partial<RenewalRuleRow>) =>
    unwrap<RenewalRuleRow>(api.post('/api/renewal-commissions/rules', body)),
  renewalRuleUpdate: (id: number, body: Partial<RenewalRuleRow>) =>
    unwrap<RenewalRuleRow>(api.put(`/api/renewal-commissions/rules/${id}`, body)),
  renewalRuleDelete: (id: number) =>
    unwrap<void>(api.delete(`/api/renewal-commissions/rules/${id}`)),
  renewalLedgers: (p: CommissionSearchParam) =>
    unwrap<PageResponse<RenewalLedgerRow>>(
      api.get('/api/renewal-commissions/ledgers', { params: p }),
    ),

  // ReinstatementCommission
  reinstatementRules: (p?: Partial<CommissionSearchParam>) =>
    unwrap<PageResponse<ReinstatementRuleRow>>(
      api.get('/api/reinstatement-commissions/rules', { params: p }),
    ),
  reinstatementRuleCreate: (body: Partial<ReinstatementRuleRow>) =>
    unwrap<ReinstatementRuleRow>(api.post('/api/reinstatement-commissions/rules', body)),
  reinstatementRuleUpdate: (id: number, body: Partial<ReinstatementRuleRow>) =>
    unwrap<ReinstatementRuleRow>(api.put(`/api/reinstatement-commissions/rules/${id}`, body)),
  reinstatementRuleDelete: (id: number) =>
    unwrap<void>(api.delete(`/api/reinstatement-commissions/rules/${id}`)),
  reinstatementLedgers: (p: CommissionSearchParam) =>
    unwrap<PageResponse<ReinstatementLedgerRow>>(
      api.get('/api/reinstatement-commissions/ledgers', { params: p }),
    ),

  // PersistencyBonus
  persistencyRules: (p?: Partial<CommissionSearchParam>) =>
    unwrap<PageResponse<PersistencyRuleRow>>(
      api.get('/api/persistency-bonus/rules', { params: p }),
    ),
  persistencyRuleCreate: (body: Partial<PersistencyRuleRow>) =>
    unwrap<PersistencyRuleRow>(api.post('/api/persistency-bonus/rules', body)),
  persistencyRuleUpdate: (id: number, body: Partial<PersistencyRuleRow>) =>
    unwrap<PersistencyRuleRow>(api.put(`/api/persistency-bonus/rules/${id}`, body)),
  persistencyRuleDelete: (id: number) =>
    unwrap<void>(api.delete(`/api/persistency-bonus/rules/${id}`)),
  persistencyBonuses: (p: CommissionSearchParam) =>
    unwrap<PageResponse<PersistencyBonusRow>>(
      api.get('/api/persistency-bonus/bonuses', { params: p }),
    ),
  persistencyBonusUpsert: (body: Partial<PersistencyBonusRow>) =>
    unwrap<PersistencyBonusRow>(api.post('/api/persistency-bonus/bonuses', body)),

  // OverrideLedger
  overrideLedgers: (p: OverrideLedgerSearchParam) =>
    unwrap<PageResponse<OverrideLedgerRow>>(
      api.get('/api/override-ledgers', { params: p }),
    ),

  // ── P7: IncomeCommission ──────────────────────────
  incomeLedgers: (p: CommissionSearchParam) =>
    unwrap<PageResponse<IncomeLedgerRow>>(
      api.get('/api/income-commissions/ledgers', { params: p }),
    ),
  incomeMargins: (p: CommissionSearchParam) =>
    unwrap<PageResponse<MarginSummaryRow>>(
      api.get('/api/income-commissions/margins', { params: p }),
    ),
  incomeMarginRecalc: (settleMonth: string) =>
    unwrap<void>(
      api.post('/api/income-commissions/margin/recalc', null, { params: { settleMonth } }),
    ),

  // ── P7: ReferralCommission ────────────────────────
  referralRules: (p?: Partial<CommissionSearchParam>) =>
    unwrap<PageResponse<ReferralRuleRow>>(
      api.get('/api/referral-commissions/rules', { params: p }),
    ),
  referralRuleCreate: (body: Partial<ReferralRuleRow>) =>
    unwrap<ReferralRuleRow>(api.post('/api/referral-commissions/rules', body)),
  referralRuleUpdate: (id: number, body: Partial<ReferralRuleRow>) =>
    unwrap<ReferralRuleRow>(api.put(`/api/referral-commissions/rules/${id}`, body)),
  referralRuleDelete: (id: number) =>
    unwrap<void>(api.delete(`/api/referral-commissions/rules/${id}`)),
  referralLedgers: (p: CommissionSearchParam) =>
    unwrap<PageResponse<ReferralLedgerRow>>(
      api.get('/api/referral-commissions/ledgers', { params: p }),
    ),

  // ── P7: SettlingSupport ───────────────────────────
  settlingRules: (p?: Partial<CommissionSearchParam>) =>
    unwrap<PageResponse<SettlingSupportRuleRow>>(
      api.get('/api/settling-supports/rules', { params: p }),
    ),
  settlingRuleCreate: (body: Partial<SettlingSupportRuleRow>) =>
    unwrap<SettlingSupportRuleRow>(api.post('/api/settling-supports/rules', body)),
  settlingRuleUpdate: (id: number, body: Partial<SettlingSupportRuleRow>) =>
    unwrap<SettlingSupportRuleRow>(api.put(`/api/settling-supports/rules/${id}`, body)),
  settlingRuleDelete: (id: number) =>
    unwrap<void>(api.delete(`/api/settling-supports/rules/${id}`)),
  settlingLedgers: (p: CommissionSearchParam) =>
    unwrap<PageResponse<SettlingSupportLedgerRow>>(
      api.get('/api/settling-supports/ledgers', { params: p }),
    ),

  // ── P7: RecognizedPerformance ─────────────────────
  conversionRates: (p?: Partial<CommissionSearchParam>) =>
    unwrap<PageResponse<ConversionRateRow>>(
      api.get('/api/recognized-performances/rates', { params: p }),
    ),
  conversionRateCreate: (body: Partial<ConversionRateRow>) =>
    unwrap<ConversionRateRow>(api.post('/api/recognized-performances/rates', body)),
  conversionRateUpdate: (id: number, body: Partial<ConversionRateRow>) =>
    unwrap<ConversionRateRow>(api.put(`/api/recognized-performances/rates/${id}`, body)),
  conversionRateDelete: (id: number) =>
    unwrap<void>(api.delete(`/api/recognized-performances/rates/${id}`)),
  recognizedLedgers: (p: CommissionSearchParam) =>
    unwrap<PageResponse<RecognizedLedgerRow>>(
      api.get('/api/recognized-performances/ledgers', { params: p }),
    ),

  // ── P7: Award ─────────────────────────────────────
  awardRules: (p?: Partial<CommissionSearchParam>) =>
    unwrap<PageResponse<AwardRuleRow>>(
      api.get('/api/awards/rules', { params: p }),
    ),
  awardRuleCreate: (body: Partial<AwardRuleRow>) =>
    unwrap<AwardRuleRow>(api.post('/api/awards/rules', body)),
  awardRuleUpdate: (id: number, body: Partial<AwardRuleRow>) =>
    unwrap<AwardRuleRow>(api.put(`/api/awards/rules/${id}`, body)),
  awardRuleDelete: (id: number) =>
    unwrap<void>(api.delete(`/api/awards/rules/${id}`)),
  awardLedgers: (p: CommissionSearchParam) =>
    unwrap<PageResponse<AwardLedgerRow>>(
      api.get('/api/awards/ledgers', { params: p }),
    ),

  // ── P7: LifeSupport ───────────────────────────────
  lifeSupportRules: (p?: Partial<CommissionSearchParam>) =>
    unwrap<PageResponse<LifeSupportRuleRow>>(
      api.get('/api/life-supports/rules', { params: p }),
    ),
  lifeSupportRuleCreate: (body: Partial<LifeSupportRuleRow>) =>
    unwrap<LifeSupportRuleRow>(api.post('/api/life-supports/rules', body)),
  lifeSupportRuleUpdate: (id: number, body: Partial<LifeSupportRuleRow>) =>
    unwrap<LifeSupportRuleRow>(api.put(`/api/life-supports/rules/${id}`, body)),
  lifeSupportRuleDelete: (id: number) =>
    unwrap<void>(api.delete(`/api/life-supports/rules/${id}`)),
  lifeSupportLedgers: (p: CommissionSearchParam) =>
    unwrap<PageResponse<LifeSupportLedgerRow>>(
      api.get('/api/life-supports/ledgers', { params: p }),
    ),

  // ── P7: BranchAllowance ───────────────────────────
  branchAllowanceRules: (p?: Partial<CommissionSearchParam>) =>
    unwrap<PageResponse<BranchAllowanceRuleRow>>(
      api.get('/api/branch-allowances/rules', { params: p }),
    ),
  branchAllowanceRuleCreate: (body: Partial<BranchAllowanceRuleRow>) =>
    unwrap<BranchAllowanceRuleRow>(api.post('/api/branch-allowances/rules', body)),
  branchAllowanceRuleUpdate: (id: number, body: Partial<BranchAllowanceRuleRow>) =>
    unwrap<BranchAllowanceRuleRow>(api.put(`/api/branch-allowances/rules/${id}`, body)),
  branchAllowanceRuleDelete: (id: number) =>
    unwrap<void>(api.delete(`/api/branch-allowances/rules/${id}`)),
  branchAllowanceLedgers: (p: CommissionSearchParam) =>
    unwrap<PageResponse<BranchAllowanceLedgerRow>>(
      api.get('/api/branch-allowances/ledgers', { params: p }),
    ),
};
