/**
 * 경조사비 관리 Server Actions
 *
 * API Endpoints:
 * - GET    /api/v1/condolence-expenses         목록 조회
 * - GET    /api/v1/condolence-expenses/summary  통계
 * - POST   /api/v1/condolence-expenses          등록
 * - PUT    /api/v1/condolence-expenses/{id}     수정
 * - DELETE /api/v1/condolence-expenses/{id}     삭제
 */

'use server';

import { buildApiUrl } from '@/lib/api/query-params';
import { executeServerAction } from '@/lib/api/execute-server-action';
import { executePaginatedAction } from '@/lib/api/execute-paginated-action';
import type { CondolenceExpense } from './types';

const BASE_PATH = '/api/v1/condolence-expenses';

// 목록 조회
export async function getCondolenceExpenses(params?: {
  year?: number;
  category?: string;
  search?: string;
  sort_by?: string;
  sort_order?: string;
  per_page?: number;
  page?: number;
}) {
  return executePaginatedAction<CondolenceExpense, CondolenceExpense>({
    url: buildApiUrl(BASE_PATH, {
      year: params?.year,
      category: params?.category !== 'all' ? params?.category : undefined,
      search: params?.search,
      sort_by: params?.sort_by,
      sort_order: params?.sort_order,
      per_page: params?.per_page,
      page: params?.page,
    }),
    transform: (item) => item,
    errorMessage: '경조사비 목록 조회에 실패했습니다.',
  });
}

// 통계
export async function getCondolenceExpenseSummary(params?: {
  year?: number;
  category?: string;
}) {
  return executeServerAction({
    url: buildApiUrl(`${BASE_PATH}/summary`, {
      year: params?.year,
      category: params?.category !== 'all' ? params?.category : undefined,
    }),
    errorMessage: '경조사비 통계 조회에 실패했습니다.',
  });
}

// 등록
export async function createCondolenceExpense(data: Record<string, unknown>) {
  return executeServerAction({
    url: buildApiUrl(BASE_PATH),
    method: 'POST',
    body: data,
    errorMessage: '경조사비 등록에 실패했습니다.',
  });
}

// 수정
export async function updateCondolenceExpense(id: number | string, data: Record<string, unknown>) {
  return executeServerAction({
    url: buildApiUrl(`${BASE_PATH}/${id}`),
    method: 'PUT',
    body: data,
    errorMessage: '경조사비 수정에 실패했습니다.',
  });
}

// 삭제
export async function deleteCondolenceExpense(id: number | string) {
  return executeServerAction({
    url: buildApiUrl(`${BASE_PATH}/${id}`),
    method: 'DELETE',
    errorMessage: '경조사비 삭제에 실패했습니다.',
  });
}
