'use server';


import { executeServerAction, type ActionResult } from '@/lib/api/execute-server-action';
import { buildApiUrl } from '@/lib/api/query-params';
import type { NoteReceivableItem, DailyAccountItem, MatchStatus } from './types';

// ===== API 응답 타입 =====
interface NoteReceivableItemApi {
  id: string;
  content: string;
  current_balance: number;
  issue_date: string;
  due_date: string;
}

interface DailyAccountItemApi {
  id: string;
  category: string;
  match_status: MatchStatus;
  carryover: number;
  income: number;
  expense: number;
  balance: number;
  currency: 'KRW' | 'USD';
}

interface DailyReportSummaryApi {
  date: string;
  day_of_week: string;
  note_receivable_total: number;
  foreign_currency_total: number;
  cash_asset_total: number;
  krw_totals: { carryover: number; income: number; expense: number; balance: number };
  usd_totals: { carryover: number; income: number; expense: number; balance: number };
}

// ===== API → Frontend 변환 =====
function transformNoteReceivable(item: NoteReceivableItemApi): NoteReceivableItem {
  return {
    id: item.id, content: item.content, currentBalance: item.current_balance,
    issueDate: item.issue_date, dueDate: item.due_date,
  };
}

function transformDailyAccount(item: DailyAccountItemApi): DailyAccountItem {
  return {
    id: item.id, category: item.category, matchStatus: item.match_status,
    carryover: item.carryover, income: item.income, expense: item.expense,
    balance: item.balance, currency: item.currency,
  };
}

// ===== 어음 및 외상매출채권 현황 조회 =====
export async function getNoteReceivables(params?: {
  date?: string;
}): Promise<{ success: boolean; data: NoteReceivableItem[]; error?: string }> {
  const result = await executeServerAction({
    url: buildApiUrl('/api/v1/daily-report/note-receivables', { date: params?.date }),
    transform: (data: NoteReceivableItemApi[]) => (data || []).map(transformNoteReceivable),
    errorMessage: '어음 현황 조회에 실패했습니다.',
  });
  return { success: result.success, data: result.data || [], error: result.error };
}

// ===== 일별 계좌 현황 조회 =====
export async function getDailyAccounts(params?: {
  date?: string;
}): Promise<{ success: boolean; data: DailyAccountItem[]; error?: string }> {
  const result = await executeServerAction({
    url: buildApiUrl('/api/v1/daily-report/daily-accounts', { date: params?.date }),
    transform: (data: DailyAccountItemApi[]) => (data || []).map(transformDailyAccount),
    errorMessage: '계좌 현황 조회에 실패했습니다.',
  });
  return { success: result.success, data: result.data || [], error: result.error };
}

// ===== 일일 보고서 요약 조회 =====
export async function getDailyReportSummary(params?: {
  date?: string;
}): Promise<ActionResult<{
  date: string;
  dayOfWeek: string;
  noteReceivableTotal: number;
  foreignCurrencyTotal: number;
  cashAssetTotal: number;
  krwTotals: { carryover: number; income: number; expense: number; balance: number };
  usdTotals: { carryover: number; income: number; expense: number; balance: number };
}>> {
  return executeServerAction({
    url: buildApiUrl('/api/v1/daily-report/summary', { date: params?.date }),
    transform: (data: DailyReportSummaryApi) => ({
      date: data.date,
      dayOfWeek: data.day_of_week,
      noteReceivableTotal: data.note_receivable_total,
      foreignCurrencyTotal: data.foreign_currency_total,
      cashAssetTotal: data.cash_asset_total,
      krwTotals: data.krw_totals,
      usdTotals: data.usd_totals,
    }),
    errorMessage: '요약 조회에 실패했습니다.',
  });
}

