/**
 * 매출/매입 현황 (Sales/Purchase) 변환
 */

import type { SalesStatusApiResponse, PurchaseStatusApiResponse } from '../types';
import type { SalesStatusData, PurchaseStatusData } from '@/components/business/CEODashboard/types';

const STATUS_MAP_SALES: Record<string, '입금완료' | '미입금' | '부분입금'> = {
  deposited: '입금완료',
  unpaid: '미입금',
  partial: '부분입금',
};

const STATUS_MAP_PURCHASE: Record<string, '결제완료' | '미결제' | '부분결제'> = {
  paid: '결제완료',
  unpaid: '미결제',
  partial: '부분결제',
};

/**
 * Sales Summary API 응답 → Frontend SalesStatusData 변환
 */
export function transformSalesStatusResponse(api: SalesStatusApiResponse): SalesStatusData {
  return {
    cumulativeSales: api.cumulative_sales,
    achievementRate: api.achievement_rate,
    yoyChange: api.yoy_change,
    monthlySales: api.monthly_sales,
    monthlyTrend: api.monthly_trend.map((item) => ({
      month: item.label,
      amount: item.amount,
    })),
    clientSales: api.client_sales.map((item) => ({
      name: item.name,
      amount: item.amount,
    })),
    dailyItems: api.daily_items.map((item) => ({
      date: item.date,
      client: item.client,
      item: item.item,
      amount: item.amount,
      status: STATUS_MAP_SALES[item.status] ?? '미입금',
    })),
    dailyTotal: api.daily_total,
  };
}

/**
 * Purchase Summary API 응답 → Frontend PurchaseStatusData 변환
 */
export function transformPurchaseStatusResponse(api: PurchaseStatusApiResponse): PurchaseStatusData {
  return {
    cumulativePurchase: api.cumulative_purchase,
    unpaidAmount: api.unpaid_amount,
    yoyChange: api.yoy_change,
    monthlyTrend: api.monthly_trend.map((item) => ({
      month: item.label,
      amount: item.amount,
    })),
    materialRatio: api.material_ratio.map((item) => ({
      name: item.name,
      value: item.value,
      percentage: item.percentage,
      color: item.color,
    })),
    dailyItems: api.daily_items.map((item) => ({
      date: item.date,
      supplier: item.supplier,
      item: item.item,
      amount: item.amount,
      status: STATUS_MAP_PURCHASE[item.status] ?? '미결제',
    })),
    dailyTotal: api.daily_total,
  };
}
