'use server';

/**
 * 거래처(영업) 서버 액션
 *
 * API Endpoints:
 * - GET /api/v1/clients/{id} - 상세 조회
 * - POST /api/v1/clients - 등록
 * - PUT /api/v1/clients/{id} - 수정
 * - DELETE /api/v1/clients/{id} - 삭제
 */

import { executeServerAction, type ActionResult } from '@/lib/api/execute-server-action';
import type { Client, ClientFormData, ClientApiResponse } from '@/hooks/useClientList';
import {
  transformClientFromApi,
  transformClientToApiCreate,
  transformClientToApiUpdate,
} from '@/hooks/useClientList';

const API_URL = process.env.NEXT_PUBLIC_API_URL;

// ===== 거래처 단건 조회 =====
export async function getClientById(id: string): Promise<ActionResult<Client>> {
  return executeServerAction({
    url: `${API_URL}/api/v1/clients/${id}`,
    transform: (data: ClientApiResponse) => transformClientFromApi(data),
    errorMessage: '거래처 조회 중 오류가 발생했습니다.',
  });
}

// ===== 거래처 생성 =====
export async function createClient(
  formData: Partial<ClientFormData>
): Promise<ActionResult<Client>> {
  return executeServerAction({
    url: `${API_URL}/api/v1/clients`,
    method: 'POST',
    body: transformClientToApiCreate(formData as ClientFormData),
    transform: (data: ClientApiResponse) => transformClientFromApi(data),
    errorMessage: '거래처 생성에 실패했습니다.',
  });
}

// ===== 거래처 수정 =====
export async function updateClient(
  id: string,
  formData: Partial<ClientFormData>
): Promise<ActionResult<Client>> {
  return executeServerAction({
    url: `${API_URL}/api/v1/clients/${id}`,
    method: 'PUT',
    body: transformClientToApiUpdate(formData as ClientFormData),
    transform: (data: ClientApiResponse) => transformClientFromApi(data),
    errorMessage: '거래처 수정에 실패했습니다.',
  });
}

// ===== 거래처 삭제 =====
export async function deleteClient(id: string): Promise<ActionResult> {
  return executeServerAction({
    url: `${API_URL}/api/v1/clients/${id}`,
    method: 'DELETE',
    errorMessage: '거래처 삭제에 실패했습니다.',
  });
}

// ===== 거래처 코드 생성 (8자리 영문+숫자) =====
export async function generateClientCode(): Promise<string> {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  let result = '';
  for (let i = 0; i < 8; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return result;
}
