'use server';

import type { Partner, PartnerStats, PartnerFilter, PartnerListResponse, PartnerFormData } from './types';
import { apiClient } from '@/lib/api';

/**
 * 주일 기업 - 거래처 관리 Server Actions
 * 표준화된 apiClient 사용 버전
 */

// ========================================
// API 응답 타입
// ========================================

interface ApiPartner {
  id: number;
  client_code: string | null;
  business_no: string | null;
  name: string;
  contact_person: string | null;
  client_type: string | null;
  business_type: string | null;
  business_item: string | null;
  address: string | null;
  phone: string | null;
  mobile: string | null;
  fax: string | null;
  email: string | null;
  manager_name: string | null;
  manager_tel: string | null;
  system_manager: string | null;
  outstanding_amount: number | null;
  is_overdue: boolean;
  has_bad_debt: boolean;
  is_active: boolean;
  created_at: string;
  updated_at: string;
}

interface ApiPartnerStats {
  total: number;
  sales: number;
  purchase: number;
  both: number;
  badDebt: number;
  normal: number;
}

// ========================================
// 타입 변환 함수
// ========================================

/**
 * client_type API → Frontend partnerType 변환
 */
function transformClientType(clientType: string | null | undefined): Partner['partnerType'] {
  const typeMap: Record<string, Partner['partnerType']> = {
    SALES: 'sales',
    PURCHASE: 'purchase',
    BOTH: 'both',
  };
  return typeMap[clientType || ''] || 'sales';
}

/**
 * partnerType Frontend → API client_type 변환
 */
function transformPartnerType(partnerType: Partner['partnerType']): string {
  const typeMap: Record<Partner['partnerType'], string> = {
    sales: 'SALES',
    purchase: 'PURCHASE',
    both: 'BOTH',
  };
  return typeMap[partnerType] || 'SALES';
}

/**
 * client_type → 구분 라벨 변환
 */
function getPartnerTypeLabel(clientType: string | null | undefined): string {
  const labelMap: Record<string, string> = {
    SALES: '매출',
    PURCHASE: '매입',
    BOTH: '복합',
  };
  return labelMap[clientType || ''] || '매출';
}

/**
 * API 응답 → Partner 타입 변환
 */
function transformPartner(apiData: ApiPartner): Partner {
  return {
    id: String(apiData.id),
    partnerCode: apiData.client_code || '',
    businessNumber: apiData.business_no || '',
    partnerName: apiData.name || '',
    representative: apiData.contact_person || '',
    partnerType: transformClientType(apiData.client_type),
    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 || '',
    manager: apiData.manager_name || '',
    managerPhone: apiData.manager_tel || '',
    systemManager: apiData.system_manager || '',
    logoUrl: null,
    logoBlob: null,
    salesPaymentDay: 0,
    creditRating: '',
    transactionGrade: '',
    taxInvoiceEmail: apiData.email || '',
    outstandingAmount: apiData.outstanding_amount || 0,
    overdueDays: apiData.is_overdue ? 30 : 0,
    overdueToggle: apiData.is_overdue,
    badDebtToggle: apiData.has_bad_debt,
    memos: [],
    documents: [],
    category: getPartnerTypeLabel(apiData.client_type),
    paymentDay: 0,
    isBadDebt: apiData.has_bad_debt,
    isActive: apiData.is_active !== false,
    createdAt: apiData.created_at || '',
    updatedAt: apiData.updated_at || '',
  };
}

/**
 * PartnerFormData → API 요청 데이터 변환
 */
function transformPartnerToApi(data: PartnerFormData): Record<string, unknown> {
  return {
    business_no: data.businessNumber,
    name: data.partnerName,
    contact_person: data.representative,
    client_type: transformPartnerType(data.partnerType),
    business_type: data.businessType,
    business_item: data.businessCategory,
    address: data.address1 + (data.address2 ? ` ${data.address2}` : ''),
    phone: data.phone,
    mobile: data.mobile,
    fax: data.fax,
    email: data.email,
    manager_name: data.manager,
    manager_tel: data.managerPhone,
    system_manager: data.systemManager,
    is_overdue: data.overdueToggle,
    is_active: true,
  };
}

// ========================================
// API 함수
// ========================================

/**
 * 거래처 목록 조회
 * GET /api/v1/clients
 */
export async function getPartnerList(filter?: PartnerFilter): Promise<{
  success: boolean;
  data?: PartnerListResponse;
  error?: string;
}> {
  try {
    const queryParams: Record<string, string> = {};

    // 검색어
    if (filter?.search) queryParams.q = filter.search;

    // 페이지네이션
    if (filter?.page) queryParams.page = String(filter.page);
    if (filter?.size) queryParams.size = String(filter.size);

    // API 응답 구조: { success, data: { data: [...], current_page, per_page, total, last_page } }
    const response = await apiClient.get<{
      success: boolean;
      data: {
        data: ApiPartner[];
        current_page: number;
        per_page: number;
        total: number;
        last_page: number;
      };
    }>('/clients', { params: queryParams });

    const paginated = response.data;
    let items = (paginated?.data || []).map(transformPartner);

    // 악성채권 필터 (프론트엔드에서 처리)
    if (filter?.badDebtFilter && filter.badDebtFilter !== 'all') {
      items = items.filter((p) => (filter.badDebtFilter === 'badDebt' ? p.isBadDebt : !p.isBadDebt));
    }

    // 정렬 (프론트엔드에서 처리)
    if (filter?.sortBy) {
      switch (filter.sortBy) {
        case 'latest':
          items.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
          break;
        case 'oldest':
          items.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
          break;
        case 'nameAsc':
          items.sort((a, b) => a.partnerName.localeCompare(b.partnerName));
          break;
        case 'nameDesc':
          items.sort((a, b) => b.partnerName.localeCompare(a.partnerName));
          break;
      }
    }

    return {
      success: true,
      data: {
        items,
        total: paginated?.total || 0,
        page: paginated?.current_page || 1,
        size: paginated?.per_page || 20,
        totalPages: paginated?.last_page || 1,
      },
    };
  } catch (error) {
    console.error('거래처 목록 조회 오류:', error);
    return { success: false, error: '거래처 목록을 불러오는데 실패했습니다.' };
  }
}

/**
 * 거래처 상세 조회
 * GET /api/v1/clients/{id}
 */
export async function getPartner(id: string): Promise<{
  success: boolean;
  data?: Partner;
  error?: string;
}> {
  try {
    // API 응답 구조: { success, data: {...single item} }
    const response = await apiClient.get<{ success: boolean; data: ApiPartner }>(`/clients/${id}`);
    return { success: true, data: transformPartner(response.data) };
  } catch (error) {
    console.error('거래처 조회 오류:', error);
    return { success: false, error: '거래처를 찾을 수 없습니다.' };
  }
}

/**
 * 거래처 등록
 * POST /api/v1/clients
 */
export async function createPartner(data: PartnerFormData): Promise<{
  success: boolean;
  data?: Partner;
  error?: string;
}> {
  try {
    const apiData = transformPartnerToApi(data);
    // API 응답 구조: { success, data: {...created item} }
    const response = await apiClient.post<{ success: boolean; data: ApiPartner }>('/clients', apiData);
    return { success: true, data: transformPartner(response.data) };
  } catch (error) {
    console.error('거래처 등록 오류:', error);
    return { success: false, error: '거래처 등록에 실패했습니다.' };
  }
}

/**
 * 거래처 수정
 * PUT /api/v1/clients/{id}
 */
export async function updatePartner(id: string, data: PartnerFormData): Promise<{
  success: boolean;
  data?: Partner;
  error?: string;
}> {
  try {
    const apiData = transformPartnerToApi(data);
    // API 응답 구조: { success, data: {...updated item} }
    const response = await apiClient.put<{ success: boolean; data: ApiPartner }>(`/clients/${id}`, apiData);
    return { success: true, data: transformPartner(response.data) };
  } catch (error) {
    console.error('거래처 수정 오류:', error);
    return { success: false, error: '거래처 수정에 실패했습니다.' };
  }
}

/**
 * 거래처 통계 조회
 * GET /api/v1/clients/stats
 */
export async function getPartnerStats(): Promise<{
  success: boolean;
  data?: PartnerStats;
  error?: string;
}> {
  try {
    // API 응답 구조: { success, data: {...stats} }
    const response = await apiClient.get<{ success: boolean; data: ApiPartnerStats }>('/clients/stats');
    const stats = response.data;

    return {
      success: true,
      data: {
        total: stats?.total || 0,
        unregistered: 0,
        badDebt: stats?.badDebt || 0,
        normal: stats?.normal || 0,
      },
    };
  } catch (error) {
    console.error('거래처 통계 조회 오류:', error);
    return { success: false, error: '통계를 불러오는데 실패했습니다.' };
  }
}

/**
 * 거래처 삭제
 * DELETE /api/v1/clients/{id}
 */
export async function deletePartner(id: string): Promise<{
  success: boolean;
  error?: string;
}> {
  try {
    await apiClient.delete(`/clients/${id}`);
    return { success: true };
  } catch (error) {
    console.error('거래처 삭제 오류:', error);
    return { success: false, error: '거래처 삭제에 실패했습니다.' };
  }
}

/**
 * 거래처 일괄 삭제
 * DELETE /api/v1/clients/bulk
 */
export async function deletePartners(ids: string[]): Promise<{
  success: boolean;
  deletedCount?: number;
  error?: string;
}> {
  try {
    await apiClient.delete('/clients/bulk', {
      data: { ids: ids.map((id) => Number(id)) },
    });
    return { success: true, deletedCount: ids.length };
  } catch (error) {
    console.error('거래처 일괄 삭제 오류:', error);
    return { success: false, error: '일괄 삭제에 실패했습니다.' };
  }
}