/**
 * 악성채권 추심관리 서버 액션
 *
 * API Endpoints:
 * - GET /api/v1/bad-debts - 목록 조회
 * - GET /api/v1/bad-debts/{id} - 상세 조회
 * - POST /api/v1/bad-debts - 등록
 * - PUT /api/v1/bad-debts/{id} - 수정
 * - DELETE /api/v1/bad-debts/{id} - 삭제
 * - PATCH /api/v1/bad-debts/{id}/toggle - 활성화 토글
 * - GET /api/v1/bad-debts/summary - 통계 조회
 */

'use server';

import { cookies } from 'next/headers';
import { revalidatePath } from 'next/cache';
import type { BadDebtRecord, CollectionStatus } from './types';

// ============================================
// API 응답 타입 정의
// ============================================

interface ApiResponse<T> {
  success: boolean;
  data: T;
  message: string;
}

interface PaginatedResponse<T> {
  current_page: number;
  data: T[];
  total: number;
  per_page: number;
  last_page: number;
}

// API 악성채권 데이터 타입
interface BadDebtApiData {
  id: number;
  tenant_id: number;
  client_id: number;
  debt_amount: string;
  status: 'collecting' | 'legal_action' | 'recovered' | 'bad_debt';
  overdue_days: number;
  occurred_at: string;
  closed_at: string | null;
  assigned_manager_id: number | null;
  is_active: boolean;
  note: string | null;
  created_at: string;
  updated_at: string;
  deleted_at: string | null;
  client?: {
    id: number;
    code: string;
    name: string;
    business_number: string | null;
    representative_name: string | null;
    client_type: string | null;
    business_type: string | null;
    business_category: string | null;
    zip_code: string | null;
    address1: string | null;
    address2: string | null;
    phone: string | null;
    mobile: string | null;
    fax: string | null;
    email: string | null;
    contact_name: string | null;
    contact_phone: string | null;
  };
  assigned_manager?: {
    id: number;
    name: string;
    department?: {
      id: number;
      name: string;
    };
    position: string | null;
    phone: string | null;
  };
  documents?: Array<{
    id: number;
    file_name: string;
    file_path: string;
    file_size: number;
    mime_type: string;
    created_at: string;
  }>;
  memos?: Array<{
    id: number;
    content: string;
    created_at: string;
    created_by: number;
    created_by_user?: {
      id: number;
      name: string;
    };
  }>;
}

// 통계 API 응답 타입
interface BadDebtSummaryApiData {
  total_amount: number;
  collecting_amount: number;
  legal_action_amount: number;
  recovered_amount: number;
  bad_debt_amount: number;
  total_count: number;
  collecting_count: number;
  legal_action_count: number;
  recovered_count: number;
  bad_debt_count: number;
}

// ============================================
// 헬퍼 함수
// ============================================

/**
 * API 헤더 생성
 */
async function getApiHeaders(): Promise<HeadersInit> {
  const cookieStore = await cookies();
  const token = cookieStore.get('access_token')?.value;

  return {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'Authorization': token ? `Bearer ${token}` : '',
    'X-API-KEY': process.env.API_KEY || '',
  };
}

/**
 * API 상태 → 프론트엔드 상태 변환
 * API: legal_action, bad_debt (snake_case)
 * Frontend: legalAction, badDebt (camelCase)
 */
function mapApiStatusToFrontend(apiStatus: string): CollectionStatus {
  switch (apiStatus) {
    case 'collecting': return 'collecting';
    case 'legal_action': return 'legalAction';
    case 'recovered': return 'recovered';
    case 'bad_debt': return 'badDebt';
    default: return 'collecting';
  }
}

/**
 * 프론트엔드 상태 → API 상태 변환
 */
function mapFrontendStatusToApi(status: CollectionStatus): string {
  switch (status) {
    case 'collecting': return 'collecting';
    case 'legalAction': return 'legal_action';
    case 'recovered': return 'recovered';
    case 'badDebt': return 'bad_debt';
    default: return 'collecting';
  }
}

/**
 * API client_type → 프론트엔드 vendorType 변환
 */
function mapClientTypeToVendorType(clientType?: string | null): 'sales' | 'purchase' | 'both' {
  switch (clientType) {
    case 'customer':
    case 'sales':
      return 'sales';
    case 'supplier':
    case 'purchase':
      return 'purchase';
    default:
      return 'both';
  }
}

/**
 * API 데이터 → 프론트엔드 타입 변환
 */
function transformApiToFrontend(apiData: BadDebtApiData): BadDebtRecord {
  const client = apiData.client;
  const manager = apiData.assigned_manager;

  return {
    id: String(apiData.id),
    vendorId: String(apiData.client_id),
    vendorCode: client?.code || '',
    vendorName: client?.name || '거래처 없음',
    businessNumber: client?.business_number || '',
    representativeName: client?.representative_name || '',
    vendorType: mapClientTypeToVendorType(client?.client_type),
    businessType: client?.business_type || '',
    businessCategory: client?.business_category || '',
    zipCode: client?.zip_code || '',
    address1: client?.address1 || '',
    address2: client?.address2 || '',
    phone: client?.phone || '',
    mobile: client?.mobile || '',
    fax: client?.fax || '',
    email: client?.email || '',
    contactName: client?.contact_name || '',
    contactPhone: client?.contact_phone || '',
    systemManager: '',
    debtAmount: parseFloat(apiData.debt_amount) || 0,
    status: mapApiStatusToFrontend(apiData.status),
    overdueDays: apiData.overdue_days || 0,
    overdueToggle: apiData.is_active,
    occurrenceDate: apiData.occurred_at,
    endDate: apiData.closed_at,
    assignedManagerId: apiData.assigned_manager_id ? String(apiData.assigned_manager_id) : null,
    assignedManager: manager ? {
      id: String(manager.id),
      departmentName: manager.department?.name || '',
      name: manager.name,
      position: manager.position || '',
      phone: manager.phone || '',
    } : null,
    settingToggle: apiData.is_active,
    files: apiData.documents?.map(doc => ({
      id: String(doc.id),
      name: doc.file_name,
      url: doc.file_path,
      type: 'additional' as const,
    })) || [],
    memos: apiData.memos?.map(memo => ({
      id: String(memo.id),
      content: memo.content,
      createdAt: memo.created_at,
      createdBy: memo.created_by_user?.name || `User ${memo.created_by}`,
    })) || [],
    createdAt: apiData.created_at,
    updatedAt: apiData.updated_at,
  };
}

/**
 * 프론트엔드 데이터 → API 요청 형식 변환
 */
function transformFrontendToApi(data: Partial<BadDebtRecord>): Record<string, unknown> {
  return {
    client_id: data.vendorId ? parseInt(data.vendorId) : null,
    debt_amount: data.debtAmount || 0,
    status: data.status ? mapFrontendStatusToApi(data.status) : 'collecting',
    overdue_days: data.overdueDays || 0,
    occurred_at: data.occurrenceDate || null,
    closed_at: data.endDate || null,
    assigned_manager_id: data.assignedManagerId ? parseInt(data.assignedManagerId) : null,
    is_active: data.settingToggle ?? true,
    note: null,
  };
}

// ============================================
// API 호출 함수
// ============================================

/**
 * 악성채권 목록 조회
 */
export async function getBadDebts(params?: {
  page?: number;
  size?: number;
  status?: string;
  client_id?: string;
}): Promise<BadDebtRecord[]> {
  try {
    const headers = await getApiHeaders();
    const searchParams = new URLSearchParams();

    if (params?.page) searchParams.set('page', String(params.page));
    if (params?.size) searchParams.set('size', String(params.size));
    if (params?.status && params.status !== 'all') {
      searchParams.set('status', mapFrontendStatusToApi(params.status as CollectionStatus));
    }
    if (params?.client_id && params.client_id !== 'all') {
      searchParams.set('client_id', params.client_id);
    }

    const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/bad-debts?${searchParams.toString()}`;

    const response = await fetch(url, {
      method: 'GET',
      headers,
      cache: 'no-store',
    });

    if (!response.ok) {
      console.error('[BadDebtActions] GET list error:', response.status);
      return [];
    }

    const result: ApiResponse<PaginatedResponse<BadDebtApiData>> = await response.json();

    if (!result.success || !result.data?.data) {
      console.warn('[BadDebtActions] No data in response');
      return [];
    }

    return result.data.data.map(transformApiToFrontend);
  } catch (error) {
    console.error('[BadDebtActions] getBadDebts error:', error);
    return [];
  }
}

/**
 * 악성채권 상세 조회
 */
export async function getBadDebtById(id: string): Promise<BadDebtRecord | null> {
  try {
    const headers = await getApiHeaders();

    const response = await fetch(
      `${process.env.NEXT_PUBLIC_API_URL}/api/v1/bad-debts/${id}`,
      {
        method: 'GET',
        headers,
        cache: 'no-store',
      }
    );

    if (!response.ok) {
      console.error('[BadDebtActions] GET detail error:', response.status);
      return null;
    }

    const result: ApiResponse<BadDebtApiData> = await response.json();

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

    return transformApiToFrontend(result.data);
  } catch (error) {
    console.error('[BadDebtActions] getBadDebtById error:', error);
    return null;
  }
}

/**
 * 악성채권 통계 조회
 */
export async function getBadDebtSummary(): Promise<BadDebtSummaryApiData | null> {
  try {
    const headers = await getApiHeaders();

    const response = await fetch(
      `${process.env.NEXT_PUBLIC_API_URL}/api/v1/bad-debts/summary`,
      {
        method: 'GET',
        headers,
        cache: 'no-store',
      }
    );

    if (!response.ok) {
      console.error('[BadDebtActions] GET summary error:', response.status);
      return null;
    }

    const result: ApiResponse<BadDebtSummaryApiData> = await response.json();

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

    return result.data;
  } catch (error) {
    console.error('[BadDebtActions] getBadDebtSummary error:', error);
    return null;
  }
}

/**
 * 악성채권 등록
 */
export async function createBadDebt(
  data: Partial<BadDebtRecord>
): Promise<{ success: boolean; data?: BadDebtRecord; error?: string }> {
  try {
    const headers = await getApiHeaders();
    const apiData = transformFrontendToApi(data);

    console.log('[BadDebtActions] POST request:', apiData);

    const response = await fetch(
      `${process.env.NEXT_PUBLIC_API_URL}/api/v1/bad-debts`,
      {
        method: 'POST',
        headers,
        body: JSON.stringify(apiData),
      }
    );

    const result = await response.json();

    if (!response.ok || !result.success) {
      return {
        success: false,
        error: result.message || '악성채권 등록에 실패했습니다.',
      };
    }

    revalidatePath('/accounting/bad-debt-collection');

    return {
      success: true,
      data: transformApiToFrontend(result.data),
    };
  } catch (error) {
    console.error('[BadDebtActions] createBadDebt error:', error);
    return {
      success: false,
      error: '서버 오류가 발생했습니다.',
    };
  }
}

/**
 * 악성채권 수정
 */
export async function updateBadDebt(
  id: string,
  data: Partial<BadDebtRecord>
): Promise<{ success: boolean; data?: BadDebtRecord; error?: string }> {
  try {
    const headers = await getApiHeaders();
    const apiData = transformFrontendToApi(data);

    console.log('[BadDebtActions] PUT request:', apiData);

    const response = await fetch(
      `${process.env.NEXT_PUBLIC_API_URL}/api/v1/bad-debts/${id}`,
      {
        method: 'PUT',
        headers,
        body: JSON.stringify(apiData),
      }
    );

    const result = await response.json();

    if (!response.ok || !result.success) {
      return {
        success: false,
        error: result.message || '악성채권 수정에 실패했습니다.',
      };
    }

    revalidatePath('/accounting/bad-debt-collection');

    return {
      success: true,
      data: transformApiToFrontend(result.data),
    };
  } catch (error) {
    console.error('[BadDebtActions] updateBadDebt error:', error);
    return {
      success: false,
      error: '서버 오류가 발생했습니다.',
    };
  }
}

/**
 * 악성채권 삭제
 */
export async function deleteBadDebt(id: string): Promise<{ success: boolean; error?: string }> {
  try {
    const headers = await getApiHeaders();

    const response = await fetch(
      `${process.env.NEXT_PUBLIC_API_URL}/api/v1/bad-debts/${id}`,
      {
        method: 'DELETE',
        headers,
      }
    );

    const result = await response.json();

    if (!response.ok || !result.success) {
      return {
        success: false,
        error: result.message || '악성채권 삭제에 실패했습니다.',
      };
    }

    revalidatePath('/accounting/bad-debt-collection');

    return { success: true };
  } catch (error) {
    console.error('[BadDebtActions] deleteBadDebt error:', error);
    return {
      success: false,
      error: '서버 오류가 발생했습니다.',
    };
  }
}

/**
 * 악성채권 활성화 토글
 */
export async function toggleBadDebt(id: string): Promise<{ success: boolean; data?: BadDebtRecord; error?: string }> {
  try {
    const headers = await getApiHeaders();

    const response = await fetch(
      `${process.env.NEXT_PUBLIC_API_URL}/api/v1/bad-debts/${id}/toggle`,
      {
        method: 'PATCH',
        headers,
      }
    );

    const result = await response.json();

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

    revalidatePath('/accounting/bad-debt-collection');

    return {
      success: true,
      data: transformApiToFrontend(result.data),
    };
  } catch (error) {
    console.error('[BadDebtActions] toggleBadDebt error:', error);
    return {
      success: false,
      error: '서버 오류가 발생했습니다.',
    };
  }
}
