/**
 * 거래처 관리 서버 액션
 *
 * 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 { isNextRedirectError } from '@/lib/utils/redirect-error';
import { serverFetch } from '@/lib/api/fetch-wrapper';
import type {
  Vendor,
  ClientApiData,
  ApiResponse,
  PaginatedResponse,
  VendorCategory,
  BadDebtStatus,
} from './types';

/**
 * API 데이터 → 프론트엔드 타입 변환
 */
function transformApiToFrontend(apiData: ClientApiData): Vendor {
  // client_type → category 변환 (API는 영문 SALES/PURCHASE/BOTH 반환)
  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';

  // bad_debt_total (bad_debts 테이블 기반) → badDebtStatus 변환
  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';
  }

  // purchase_payment_day 문자열 → 숫자 변환
  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,

    // 신용/거래 정보 (API에 없는 필드는 기본값)
    creditRating: 'A',
    transactionGrade: 'C',
    taxInvoiceEmail: apiData.email || '',
    bankName: '',
    accountNumber: apiData.account_id || '',
    accountHolder: apiData.name || '',

    // 미수금/악성채권 정보 (API에서 계산된 값 사용)
    outstandingAmount: apiData.outstanding_amount || 0,
    overdueAmount: 0,
    overdueDays: 0,
    unpaidAmount: 0,
    badDebtAmount: badDebtTotal,  // bad_debts 테이블 기반 악성채권 합계
    badDebtStatus,
    overdueToggle: apiData.is_overdue ?? false,  // API의 is_overdue 값 사용
    badDebtToggle: hasBadDebt,

    // 메모
    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> {
  // category → client_type 변환 (API는 영문 SALES/PURCHASE/BOTH 기대)
  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: true,
  };
}

/**
 * 거래처 목록 조회
 */
export async function getClients(params?: {
  page?: number;
  size?: number;
  q?: string;
  only_active?: boolean;
}): Promise<{ success: boolean; data: Vendor[]; total: number; error?: string }> {
  const searchParams = new URLSearchParams();

  if (params?.page) searchParams.set('page', String(params.page));
  if (params?.size) searchParams.set('size', String(params.size));
  if (params?.q) searchParams.set('q', params.q);
  if (params?.only_active !== undefined) searchParams.set('only_active', String(params.only_active));

  const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/clients?${searchParams.toString()}`;
  console.log('[VendorActions] GET clients:', url);

  const { response, error } = await serverFetch(url, { method: 'GET' });

  if (error) {
    return { success: false, data: [], total: 0, error: error.message };
  }

  if (!response?.ok) {
    console.error('[VendorActions] GET clients error:', response?.status);
    return { success: false, data: [], total: 0, error: `HTTP ${response?.status}` };
  }

  const result: ApiResponse<PaginatedResponse<ClientApiData>> = await response.json();
  console.log('[VendorActions] GET clients response:', result.success, result.data?.total);

  if (!result.success || !result.data) {
    return { success: false, data: [], total: 0, error: result.message };
  }

  const vendors = result.data.data.map(transformApiToFrontend);

  return { success: true, data: vendors, total: result.data.total };
}

/**
 * 거래처 상세 조회
 */
export async function getClientById(id: string): Promise<Vendor | null> {
  const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/clients/${id}`;
  const { response, error } = await serverFetch(url, { method: 'GET' });

  if (error || !response?.ok) {
    console.error('[VendorActions] GET client error:', error?.message || response?.status);
    return null;
  }

  const result: ApiResponse<ClientApiData> = await response.json();
  console.log('[VendorActions] GET client response:', result.success);

  if (!result.success || !result.data) {
    return null;
  }

  return transformApiToFrontend(result.data);
}

/**
 * 거래처 등록
 */
export async function createClient(
  data: Partial<Vendor>
): Promise<{ success: boolean; data?: Vendor; error?: string }> {
  const apiData = transformFrontendToApi(data);
  console.log('[VendorActions] POST client request:', apiData);

  const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/clients`;
  const { response, error } = await serverFetch(url, {
    method: 'POST',
    body: JSON.stringify(apiData),
  });

  if (error) {
    return { success: false, error: error.message };
  }

  const result = await response?.json();
  console.log('[VendorActions] POST client response:', result);

  if (!response?.ok || !result.success) {
    return { success: false, error: result?.message || '거래처 등록에 실패했습니다.' };
  }

  return { success: true, data: transformApiToFrontend(result.data) };
}

/**
 * 거래처 수정
 */
export async function updateClient(
  id: string,
  data: Partial<Vendor>
): Promise<{ success: boolean; data?: Vendor; error?: string }> {
  const apiData = transformFrontendToApi(data);
  console.log('[VendorActions] PUT client request:', apiData);

  const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/clients/${id}`;
  const { response, error } = await serverFetch(url, {
    method: 'PUT',
    body: JSON.stringify(apiData),
  });

  if (error) {
    return { success: false, error: error.message };
  }

  const result = await response?.json();
  console.log('[VendorActions] PUT client response:', result);

  if (!response?.ok || !result.success) {
    return { success: false, error: result?.message || '거래처 수정에 실패했습니다.' };
  }

  return { success: true, data: transformApiToFrontend(result.data) };
}

/**
 * 거래처 삭제
 */
export async function deleteClient(id: string): Promise<{ success: boolean; error?: string }> {
  const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/clients/${id}`;
  const { response, error } = await serverFetch(url, { method: 'DELETE' });

  if (error) {
    return { success: false, error: error.message };
  }

  const result = await response?.json();
  console.log('[VendorActions] DELETE client response:', result);

  if (!response?.ok || !result.success) {
    return { success: false, error: result?.message || '거래처 삭제에 실패했습니다.' };
  }

  return { success: true };
}

/**
 * 거래처 활성/비활성 토글
 */
export async function toggleClientActive(id: string): Promise<{ success: boolean; data?: Vendor; error?: string }> {
  const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/clients/${id}/toggle`;
  const { response, error } = await serverFetch(url, { method: 'PATCH' });

  if (error) {
    return { success: false, error: error.message };
  }

  const result = await response?.json();
  console.log('[VendorActions] PATCH toggle response:', result);

  if (!response?.ok || !result.success) {
    return { success: false, error: result?.message || '상태 변경에 실패했습니다.' };
  }

  return { success: true, data: transformApiToFrontend(result.data) };
}
