import type {
  SubscriptionApiData,
  UsageApiData,
  SubscriptionInfo,
  SubscriptionStatus,
} from './types';
import { mapPlanCodeToType } from './types';

// ===== 바이트 → 읽기 쉬운 단위 변환 =====
export function formatBytes(bytes: number): string {
  if (bytes === 0) return '0 B';

  const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
  const k = 1024;
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  const value = bytes / Math.pow(k, i);

  const formatted = value % 1 === 0 ? value.toString() : value.toFixed(2).replace(/\.?0+$/, '');

  return `${formatted} ${units[i]}`;
}

// ===== 토큰 수 포맷: 1,000,000 → "1.0M", 496,000 → "496K" =====
export function formatTokenCount(tokens: number): string {
  if (tokens >= 1_000_000) return `${(tokens / 1_000_000).toFixed(1)}M`;
  if (tokens >= 1_000) return `${Math.round(tokens / 1_000).toLocaleString()}K`;
  return tokens.toLocaleString();
}

// ===== 원화 포맷: 1234 → "₩1,234" =====
export function formatKrw(amount: number): string {
  return `₩${Math.round(amount).toLocaleString()}`;
}

// ===== 월 표시: "2026-03" → "2026년 3월" =====
export function formatPeriod(period: string): string {
  const [year, month] = period.split('-');
  return `${year}년 ${parseInt(month)}월`;
}

// ===== Progress Bar 색상 결정 =====
export function getProgressColor(percentage: number): string {
  if (percentage > 100) return 'bg-red-500';
  if (percentage >= 80) return 'bg-orange-500';
  if (percentage >= 60) return 'bg-yellow-500';
  return 'bg-blue-500';
}

// ===== API → Frontend 변환 =====
export function transformApiToFrontend(
  subscriptionData: SubscriptionApiData | null,
  usageData: UsageApiData | null
): SubscriptionInfo {
  const plan = subscriptionData?.plan;
  const planType = mapPlanCodeToType(plan?.code || null);

  const price = plan?.price;
  const monthlyFee = typeof price === 'string' ? parseFloat(price) : (price || 0);

  const status = (subscriptionData?.status || 'pending') as SubscriptionStatus;

  // usage API의 subscription 데이터 (통합 응답)
  const usageSub = usageData?.subscription;

  // AI 토큰 기본값
  const aiTokensRaw = usageData?.ai_tokens;
  const aiTokens = {
    period: aiTokensRaw?.period || '',
    totalTokens: aiTokensRaw?.total_tokens || 0,
    limit: aiTokensRaw?.limit || 1_000_000,
    percentage: aiTokensRaw?.percentage || 0,
    costKrw: aiTokensRaw?.cost_krw || 0,
    warningThreshold: aiTokensRaw?.warning_threshold || 80,
    isOverLimit: aiTokensRaw?.is_over_limit || false,
    byModel: aiTokensRaw?.by_model || [],
  };

  return {
    id: subscriptionData?.id,

    // 구독 플랜 정보
    plan: planType,
    planName: usageSub?.plan || plan?.name || PLAN_LABELS_LOCAL[planType],
    monthlyFee: usageSub?.monthly_fee ?? monthlyFee,
    status: (usageSub?.status as SubscriptionStatus) || status,
    startedAt: usageSub?.started_at || subscriptionData?.started_at || null,
    endedAt: usageSub?.ended_at || subscriptionData?.ended_at || null,
    remainingDays: usageSub?.remaining_days ?? null,

    // 사용자
    userCount: usageData?.users?.used ?? 0,
    userLimit: usageData?.users?.limit === 0 ? null : (usageData?.users?.limit ?? null),

    // 저장공간
    storageUsed: usageData?.storage?.used ?? 0,
    storageLimit: usageData?.storage?.limit || 107_374_182_400,
    storageUsedFormatted: usageData?.storage?.used_formatted || formatBytes(usageData?.storage?.used ?? 0),
    storageLimitFormatted: usageData?.storage?.limit_formatted || '100 GB',
    storagePercentage: usageData?.storage?.percentage ?? 0,

    // AI 토큰
    aiTokens,
  };
}

// 로컬 플랜 라벨 (순환 참조 방지)
const PLAN_LABELS_LOCAL: Record<string, string> = {
  free: '무료',
  basic: '베이직',
  premium: '프리미엄',
  enterprise: '엔터프라이즈',
};
