import type { PaymentApiData, PaymentHistory, PaymentStatus } from './types';
import { PAYMENT_METHOD_LABELS } from './types';
import { formatDate, toDateString } from '@/lib/utils/date';

// ===== API → Frontend 변환 =====
export function transformApiToFrontend(apiData: PaymentApiData): PaymentHistory {
  const subscription = apiData.subscription;
  const plan = subscription?.plan;

  // 결제 수단 라벨 생성
  const paymentMethodLabel = PAYMENT_METHOD_LABELS[apiData.payment_method] || apiData.payment_method;

  // 구독 기간
  const periodStart = toDateString(subscription?.started_at);
  const periodEnd = toDateString(subscription?.ended_at);

  return {
    id: String(apiData.id),
    paymentDate: toDateString(apiData.paid_at) || formatDate(apiData.created_at),
    subscriptionName: plan?.name || '구독',
    paymentMethod: paymentMethodLabel,
    subscriptionPeriod: {
      start: periodStart,
      end: periodEnd,
    },
    amount: typeof apiData.amount === 'string' ? parseFloat(apiData.amount) : apiData.amount,
    status: apiData.status as PaymentStatus,
    canViewInvoice: apiData.status === 'completed',
    createdAt: apiData.created_at,
    updatedAt: apiData.updated_at,
  };
}