'use server';

import { executeServerAction, type ActionResult } from '@/lib/api/execute-server-action';
import { buildApiUrl } from '@/lib/api/query-params';
import type {
  IncomeStatementResponseApi,
  IncomeStatementMonthlyResponseApi,
  IncomeStatementSectionApi,
  IncomeStatementData,
  IncomeStatementMonthlyData,
  IncomeStatementSection,
  UnitType,
} from './types';

function transformSection(s: IncomeStatementSectionApi): IncomeStatementSection {
  return {
    code: s.code,
    name: s.name,
    currentAmount: s.current_amount,
    previousAmount: s.previous_amount,
    items: s.items || [],
    isCalculated: s.is_calculated,
  };
}

export async function getIncomeStatement(params: {
  startDate: string;
  endDate: string;
  unit?: UnitType;
}): Promise<ActionResult<IncomeStatementData>> {
  return executeServerAction({
    url: buildApiUrl('/api/v1/income-statement', {
      start_date: params.startDate,
      end_date: params.endDate,
      unit: params.unit,
    }),
    transform: (data: IncomeStatementResponseApi): IncomeStatementData => ({
      period: {
        current: data.period.current,
        previous: data.period.previous,
      },
      unit: data.unit,
      sections: data.sections.map(transformSection),
    }),
    errorMessage: '손익계산서 조회에 실패했습니다.',
  });
}

export async function getMonthlyIncomeStatement(params: {
  year: number;
  unit?: UnitType;
}): Promise<ActionResult<IncomeStatementMonthlyData>> {
  return executeServerAction({
    url: buildApiUrl('/api/v1/income-statement/monthly', {
      year: params.year,
      unit: params.unit,
    }),
    transform: (data: IncomeStatementMonthlyResponseApi): IncomeStatementMonthlyData => ({
      year: data.year,
      fiscalYear: data.fiscal_year,
      fiscalLabel: data.fiscal_label,
      unit: data.unit,
      months: data.months.map((m) => ({
        month: m.month,
        label: m.label,
        sections: m.sections.map(transformSection),
      })),
    }),
    errorMessage: '월별 손익계산서 조회에 실패했습니다.',
  });
}
