/**
 * 미수금 (Receivable) + 채권추심 (DebtCollection) 변환
 */

import type { ReceivablesApiResponse, BadDebtApiResponse } from '../types';
import type {
  ReceivableData,
  DebtCollectionData,
  CheckPoint,
  CheckPointType,
} from '@/components/business/CEODashboard/types';
import { formatAmount, normalizePath, validateHighlightColor } from './common';

// ============================================
// 미수금 (Receivable) — D1.7 cards + check_points 구조
// ============================================

/**
 * Receivables API 응답 → Frontend 타입 변환
 * 백엔드에서 cards[] + check_points[] 구조로 직접 전달
 */
export function transformReceivableResponse(api: ReceivablesApiResponse): ReceivableData {
  return {
    cards: api.cards.map((card) => ({
      id: card.id,
      label: card.label,
      amount: card.amount,
      subLabel: card.subLabel,
      unit: card.unit,
      // sub_items → subItems 매핑
      subItems: card.sub_items?.map((item) => ({
        label: item.label,
        value: item.value,
      })),
      // top_items → subItems 매핑 (Top 3 거래처)
      ...(card.top_items && card.top_items.length > 0
        ? {
            subItems: card.top_items.map((item, idx) => ({
              label: `${idx + 1}. ${item.name}`,
              value: item.amount,
            })),
          }
        : {}),
    })),
    checkPoints: api.check_points.map((cp) => ({
      id: cp.id,
      type: cp.type as CheckPointType,
      message: cp.message,
      highlights: cp.highlights?.map((h) => ({
        text: h.text,
        color: validateHighlightColor(h.color),
      })),
    })),
    detailButtonPath: normalizePath('/accounting/receivables-status'),
  };
}

// ============================================
// 채권추심 (DebtCollection)
// ============================================

/**
 * 채권추심 CheckPoints 생성
 */
function generateDebtCollectionCheckPoints(api: BadDebtApiResponse): CheckPoint[] {
  const checkPoints: CheckPoint[] = [];

  // 법적조치 진행 중
  if (api.legal_action_amount > 0) {
    checkPoints.push({
      id: 'dc-legal',
      type: 'warning' as CheckPointType,
      message: `법적조치 진행 중 ${formatAmount(api.legal_action_amount)}입니다.`,
      highlights: [
        { text: formatAmount(api.legal_action_amount), color: 'red' as const },
      ],
    });
  }

  // 회수 완료
  if (api.recovered_amount > 0) {
    checkPoints.push({
      id: 'dc-recovered',
      type: 'success' as CheckPointType,
      message: `총 ${formatAmount(api.recovered_amount)}을 회수 완료했습니다.`,
      highlights: [
        { text: formatAmount(api.recovered_amount), color: 'green' as const },
        { text: '회수 완료', color: 'green' as const },
      ],
    });
  }

  return checkPoints;
}

/**
 * 채권추심 subLabel: 백엔드 sub_labels 필드 직접 사용
 */
function buildDebtSubLabel(cardId: string, subLabels?: Record<string, string | null>): string | undefined {
  return subLabels?.[cardId] || undefined;
}

/**
 * BadDebt API 응답 → Frontend 타입 변환
 */
export function transformDebtCollectionResponse(api: BadDebtApiResponse): DebtCollectionData {
  return {
    cards: [
      {
        id: 'dc1',
        label: '누적 악성채권',
        amount: api.total_amount,
        subLabel: buildDebtSubLabel('dc1', api.sub_labels),
      },
      {
        id: 'dc2',
        label: '추심중',
        amount: api.collecting_amount,
        subLabel: buildDebtSubLabel('dc2', api.sub_labels),
      },
      {
        id: 'dc3',
        label: '법적조치',
        amount: api.legal_action_amount,
        subLabel: buildDebtSubLabel('dc3', api.sub_labels),
      },
      {
        id: 'dc4',
        label: '회수완료',
        amount: api.recovered_amount,
        subLabel: buildDebtSubLabel('dc4', api.sub_labels),
      },
    ],
    checkPoints: generateDebtCollectionCheckPoints(api),
    detailButtonPath: normalizePath('/accounting/bad-debt-collection'),
  };
}
