/**
 * 거래처 관리 서버 액션
 *
 * API Endpoints:
 * - GET /api/v1/clients - 목록 조회
 * - GET /api/v1/clients/{id} - 상세 조회
 * - POST /api/v1/clients - 등록
 * - PUT /api/v1/clients/{id} - 수정
 * - DELETE /api/v1/clients/{id} - 삭제
 * - PATCH /api/v1/clients/{id}/toggle - 활성/비활성 토글
 */

'use server';


import { executeServerAction, type ActionResult } from '@/lib/api/execute-server-action';
import { buildApiUrl } from '@/lib/api/query-params';
import type {
  Vendor,
  ClientApiData,
  PaginatedResponse,
  VendorCategory,
  BadDebtStatus,
} from './types';

/**
 * API 데이터 → 프론트엔드 타입 변환
 */
function transformApiToFrontend(apiData: ClientApiData): Vendor {
  let category: VendorCategory = 'both';
  if (apiData.client_type === 'PURCHASE') category = 'purchase';
  else if (apiData.client_type === 'SALES') category = 'sales';
  else if (apiData.client_type === 'BOTH') category = 'both';

  const badDebtTotal = apiData.bad_debt_total ?? 0;
  const hasBadDebt = apiData.has_bad_debt ?? badDebtTotal > 0;
  let badDebtStatus: BadDebtStatus = 'none';
  if (hasBadDebt) {
    badDebtStatus = 'badDebt';
  } else if (apiData.outstanding_amount && apiData.outstanding_amount > 0) {
    badDebtStatus = 'normal';
  }

  const purchasePaymentDay = apiData.purchase_payment_day
    ? parseInt(apiData.purchase_payment_day.replace(/[^0-9]/g, '')) || 25
    : 25;
  const salesPaymentDay = apiData.sales_payment_day
    ? parseInt(apiData.sales_payment_day.replace(/[^0-9]/g, '')) || 25
    : 25;

  return {
    id: String(apiData.id),
    vendorCode: apiData.client_code || '',
    businessNumber: apiData.business_no || '',
    vendorName: apiData.name || '',
    representativeName: apiData.contact_person || '',
    category,
    businessType: apiData.business_type || '',
    businessCategory: apiData.business_item || '',
    zipCode: '',
    address1: apiData.address || '',
    address2: '',
    phone: apiData.phone || '',
    mobile: apiData.mobile || '',
    fax: apiData.fax || '',
    email: apiData.email || '',
    managerName: apiData.manager_name || '',
    managerPhone: apiData.manager_tel || '',
    systemManager: apiData.system_manager || '',
    logoUrl: '',
    purchasePaymentDay,
    salesPaymentDay,
    creditRating: 'A',
    transactionGrade: 'C',
    taxInvoiceEmail: apiData.email || '',
    bankName: '',
    accountNumber: apiData.account_id || '',
    accountHolder: apiData.name || '',
    outstandingAmount: apiData.outstanding_amount || 0,
    overdueAmount: 0,
    overdueDays: 0,
    unpaidAmount: 0,
    badDebtAmount: badDebtTotal,
    badDebtStatus,
    overdueToggle: apiData.is_overdue ?? false,
    badDebtToggle: hasBadDebt,
    isActive: apiData.is_active ?? true,
    memos: apiData.memo ? [{ id: '1', content: apiData.memo, createdAt: apiData.created_at }] : [],
    createdAt: apiData.created_at,
    updatedAt: apiData.updated_at,
  };
}

/**
 * 프론트엔드 데이터 → API 요청 형식 변환
 */
function transformFrontendToApi(data: Partial<Vendor>): Record<string, unknown> {
  let clientType: string | null = null;
  if (data.category === 'purchase') clientType = 'PURCHASE';
  else if (data.category === 'sales') clientType = 'SALES';
  else if (data.category === 'both') clientType = 'BOTH';

  return {
    client_code: data.vendorCode || null,
    name: data.vendorName || '',
    client_type: clientType,
    contact_person: data.representativeName || null,
    phone: data.phone || null,
    mobile: data.mobile || null,
    fax: data.fax || null,
    email: data.email || null,
    address: data.address1 ? `${data.address1} ${data.address2 || ''}`.trim() : null,
    manager_name: data.managerName || null,
    manager_tel: data.managerPhone || null,
    system_manager: data.systemManager || null,
    purchase_payment_day: data.purchasePaymentDay ? `${data.purchasePaymentDay}일` : null,
    sales_payment_day: data.salesPaymentDay ? `${data.salesPaymentDay}일` : null,
    business_no: data.businessNumber || null,
    business_type: data.businessType || null,
    business_item: data.businessCategory || null,
    bad_debt: data.badDebtToggle || false,
    is_overdue: data.overdueToggle ?? false,
    memo: data.memos?.[0]?.content || null,
    is_active: data.isActive ?? true,
  };
}

// ===== 거래처 목록 조회 =====
export async function getClients(params?: {
  page?: number;
  size?: number;
  q?: string;
  only_active?: boolean;
  start_date?: string;
  end_date?: string;
}): Promise<{ success: boolean; data: Vendor[]; total: number; error?: string }> {
  const result = await executeServerAction({
    url: buildApiUrl('/api/v1/clients', {
      page: params?.page,
      size: params?.size,
      q: params?.q,
      only_active: params?.only_active,
      start_date: params?.start_date,
      end_date: params?.end_date,
    }),
    transform: (data: PaginatedResponse<ClientApiData>) => ({
      items: data.data.map(transformApiToFrontend),
      total: data.total,
    }),
    errorMessage: '거래처 목록 조회에 실패했습니다.',
  });
  return {
    success: result.success,
    data: result.data?.items || [],
    total: result.data?.total || 0,
    error: result.error,
  };
}

// ===== 거래처 상세 조회 =====
export async function getClientById(id: string): Promise<Vendor | null> {
  const result = await executeServerAction({
    url: buildApiUrl(`/api/v1/clients/${id}`),
    transform: (data: ClientApiData) => transformApiToFrontend(data),
    errorMessage: '거래처 조회에 실패했습니다.',
  });
  return result.data || null;
}

// ===== 거래처 등록 =====
export async function createClient(
  data: Partial<Vendor>
): Promise<ActionResult<Vendor>> {
  return executeServerAction({
    url: buildApiUrl('/api/v1/clients'),
    method: 'POST',
    body: transformFrontendToApi(data),
    transform: (data: ClientApiData) => transformApiToFrontend(data),
    errorMessage: '거래처 등록에 실패했습니다.',
  });
}

// ===== 거래처 수정 =====
export async function updateClient(
  id: string,
  data: Partial<Vendor>
): Promise<ActionResult<Vendor>> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/clients/${id}`),
    method: 'PUT',
    body: transformFrontendToApi(data),
    transform: (data: ClientApiData) => transformApiToFrontend(data),
    errorMessage: '거래처 수정에 실패했습니다.',
  });
}

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

// ===== 거래처 활성/비활성 토글 =====
export async function toggleClientActive(id: string): Promise<ActionResult<Vendor>> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/clients/${id}/toggle`),
    method: 'PATCH',
    transform: (data: ClientApiData) => transformApiToFrontend(data),
    errorMessage: '상태 변경에 실패했습니다.',
  });
}
