/**
 * 상품권 관리 서버 액션
 *
 * API Endpoints (Loan API 재사용, category='gift_certificate'):
 * - GET /api/v1/loans?category=gift_certificate - 목록 조회
 * - GET /api/v1/loans/{id} - 상세 조회
 * - POST /api/v1/loans - 등록
 * - PUT /api/v1/loans/{id} - 수정
 * - DELETE /api/v1/loans/{id} - 삭제
 * - GET /api/v1/loans/summary?category=gift_certificate - 요약 통계
 */

'use server';

import { executeServerAction, type ActionResult } from '@/lib/api/execute-server-action';
import { executePaginatedAction, type PaginatedActionResult } from '@/lib/api/execute-paginated-action';
import { buildApiUrl } from '@/lib/api/query-params';
import type {
  GiftCertificateRecord,
  GiftCertificateFormData,
  LoanApiData,
} from './types';
import {
  transformApiToRecord,
  transformApiToFormData,
  transformFormToApi,
} from './types';

// ===== 상품권 목록 조회 =====
export async function getGiftCertificates(params?: {
  page?: number;
  perPage?: number;
  startDate?: string;
  endDate?: string;
  status?: string;
  search?: string;
}): Promise<PaginatedActionResult<GiftCertificateRecord>> {
  return executePaginatedAction<LoanApiData, GiftCertificateRecord>({
    url: buildApiUrl('/api/v1/loans', {
      category: 'gift_certificate',
      page: params?.page,
      per_page: params?.perPage,
      start_date: params?.startDate,
      end_date: params?.endDate,
      status: params?.status && params.status !== 'all' ? params.status : undefined,
      search: params?.search,
    }),
    transform: transformApiToRecord,
    errorMessage: '상품권 목록 조회에 실패했습니다.',
  });
}

// ===== 상품권 상세 조회 =====
export async function getGiftCertificateById(
  id: string
): Promise<ActionResult<GiftCertificateFormData>> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/loans/${id}`),
    transform: (data: LoanApiData) => transformApiToFormData(data),
    errorMessage: '상품권 조회에 실패했습니다.',
  });
}

// ===== 상품권 등록 =====
export async function createGiftCertificate(
  data: GiftCertificateFormData
): Promise<ActionResult<GiftCertificateRecord>> {
  return executeServerAction({
    url: buildApiUrl('/api/v1/loans'),
    method: 'POST',
    body: transformFormToApi(data),
    transform: (d: LoanApiData) => transformApiToRecord(d),
    errorMessage: '상품권 등록에 실패했습니다.',
  });
}

// ===== 상품권 수정 =====
export async function updateGiftCertificate(
  id: string,
  data: GiftCertificateFormData
): Promise<ActionResult<GiftCertificateRecord>> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/loans/${id}`),
    method: 'PUT',
    body: transformFormToApi(data),
    transform: (d: LoanApiData) => transformApiToRecord(d),
    errorMessage: '상품권 수정에 실패했습니다.',
  });
}

// ===== 상품권 삭제 =====
export async function deleteGiftCertificate(
  id: string
): Promise<ActionResult> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/loans/${id}`),
    method: 'DELETE',
    errorMessage: '상품권 삭제에 실패했습니다.',
  });
}

// ===== 상품권 요약 통계 =====
export async function getGiftCertificateSummary(params?: {
  startDate?: string;
  endDate?: string;
}): Promise<ActionResult<{
  totalCount: number;
  totalAmount: number;
  holdingCount: number;
  holdingAmount: number;
  usedCount: number;
  usedAmount: number;
  entertainmentCount: number;
  entertainmentAmount: number;
}>> {
  return executeServerAction({
    url: buildApiUrl('/api/v1/loans/summary', {
      category: 'gift_certificate',
      start_date: params?.startDate,
      end_date: params?.endDate,
    }),
    transform: (data: {
      total_count: number;
      total_amount: number;
      holding_count?: number;
      holding_amount?: number;
      used_count?: number;
      used_amount?: number;
      entertainment_count?: number;
      entertainment_amount?: number;
    }) => ({
      totalCount: data.total_count ?? 0,
      totalAmount: data.total_amount ?? 0,
      holdingCount: data.holding_count ?? 0,
      holdingAmount: data.holding_amount ?? 0,
      usedCount: data.used_count ?? 0,
      usedAmount: data.used_amount ?? 0,
      entertainmentCount: data.entertainment_count ?? 0,
      entertainmentAmount: data.entertainment_amount ?? 0,
    }),
    errorMessage: '상품권 요약 조회에 실패했습니다.',
  });
}
