'use server';

import type { Order, OrderStats, OrderDetail, OrderDetailFormData, OrderStatus, OrderType } from './types';
import { apiClient } from '@/lib/api';
import type { CommonCode } from '@/lib/api/common-codes';
import { toCommonCodeOptions } from '@/lib/api/common-codes';
import { formatDate } from '@/lib/utils/date';

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

/**
 * Backend status_code → Frontend OrderStatus 변환
 * DRAFT → waiting, CONFIRMED → order_complete, IN_PROGRESS → delivery_scheduled, COMPLETED → delivery_complete
 */
function transformStatus(backendStatus: string | null | undefined): OrderStatus {
  const statusMap: Record<string, OrderStatus> = {
    DRAFT: 'waiting',
    CONFIRMED: 'order_complete',
    IN_PROGRESS: 'delivery_scheduled',
    COMPLETED: 'delivery_complete',
    CANCELLED: 'waiting', // 취소는 대기로 표시
  };
  return statusMap[backendStatus?.toUpperCase() || ''] || 'waiting';
}

/**
 * Frontend OrderStatus → Backend status_code 변환
 */
function transformToBackendStatus(frontendStatus: OrderStatus): string {
  const statusMap: Record<OrderStatus, string> = {
    waiting: 'DRAFT',
    order_complete: 'CONFIRMED',
    delivery_scheduled: 'IN_PROGRESS',
    delivery_complete: 'COMPLETED',
  };
  return statusMap[frontendStatus] || 'DRAFT';
}

/**
 * Backend order_type_code → Frontend OrderType 변환
 */
function transformOrderType(backendType: string | null | undefined): OrderType {
  // Backend: ORDER, PURCHASE
  // Frontend: steel_bar, material, outsourcing
  // 현재 Backend는 ORDER/PURCHASE만 있으므로 options에서 가져오거나 기본값 사용
  const typeMap: Record<string, OrderType> = {
    ORDER: 'steel_bar',
    PURCHASE: 'material',
  };
  return typeMap[backendType?.toUpperCase() || ''] || 'steel_bar';
}

/**
 * Frontend OrderType → Backend order_type_code 변환
 */
function transformToBackendOrderType(frontendType: OrderType): string {
  const typeMap: Record<OrderType, string> = {
    steel_bar: 'ORDER',
    material: 'PURCHASE',
    outsourcing: 'ORDER',
  };
  return typeMap[frontendType] || 'ORDER';
}

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

interface ApiOrder {
  id: number;
  order_no: string;
  client_id: number | null;
  client_name: string | null;
  client?: { id: number; name: string } | null;
  site_name: string | null;
  status_code: string;
  order_type_code: string;
  received_at: string | null;
  delivery_date: string | null;
  actual_delivery_date: string | null;
  total_amount: number | null;
  supply_amount: number | null;
  tax_amount: number | null;
  memo: string | null;
  created_at: string;
  updated_at: string;
  items?: ApiOrderItem[];
  quote?: { id: number; quote_no: string; site_name: string } | null;
}

interface ApiOrderItem {
  id: number;
  item_id: number | null;
  item_name: string;
  specification: string | null;
  quantity: number;
  unit: string | null;
  unit_price: number;
  supply_amount: number;
  tax_amount: number;
  total_amount: number;
  sort_order: number;
}

interface ApiOrderStats {
  total: number;
  draft: number;
  confirmed: number;
  in_progress: number;
  completed: number;
  cancelled: number;
  total_amount: number;
  confirmed_amount: number;
}

/**
 * API 응답 → Order 타입 변환
 */
function transformOrder(apiOrder: ApiOrder): Order {
  return {
    id: String(apiOrder.id),
    contractNumber: apiOrder.quote?.quote_no || '',
    partnerId: apiOrder.client_id ? String(apiOrder.client_id) : '',
    partnerName: apiOrder.client?.name || apiOrder.client_name || '',
    siteName: apiOrder.site_name || '',
    name: apiOrder.items?.[0]?.item_name || '',
    constructionPM: '', // Backend에 없음 - options로 확장 가능
    orderManager: '', // Backend에 없음 - options로 확장 가능
    orderNumber: apiOrder.order_no,
    orderCompany: '', // Backend에 없음 - options로 확장 가능
    workTeamLeader: '', // Backend에 없음 - options로 확장 가능
    constructionStartDate: apiOrder.received_at || '',
    orderType: transformOrderType(apiOrder.order_type_code),
    item: apiOrder.items?.[0]?.item_name || '',
    quantity: apiOrder.items?.[0]?.quantity || 0,
    orderDate: apiOrder.received_at || '',
    plannedDeliveryDate: apiOrder.delivery_date || '',
    actualDeliveryDate: apiOrder.actual_delivery_date || null,
    status: transformStatus(apiOrder.status_code),
    // 달력 표시용 기간: received_at ~ delivery_date
    // received_at이 없으면 delivery_date를 시작일로 사용 (단일 날짜 이벤트)
    // delivery_date도 없으면 created_at을 사용
    periodStart: apiOrder.received_at || apiOrder.delivery_date || formatDate(apiOrder.created_at),
    periodEnd: apiOrder.delivery_date || apiOrder.received_at || formatDate(apiOrder.created_at),
    createdAt: apiOrder.created_at,
    updatedAt: apiOrder.updated_at,
  };
}

/**
 * API 응답 → OrderDetail 타입 변환
 */
function transformOrderDetail(apiOrder: ApiOrder): OrderDetail {
  const baseOrder = transformOrder(apiOrder);

  return {
    ...baseOrder,
    orderCompanyId: '', // Backend에 없음
    deliveryLocationType: 'site',
    deliveryAddress: '', // Backend에 없음
    contractId: '',
    constructionPMId: '',
    constructionManagers: [],
    orderItems: [],
    scheduleEvents: [],
    memo: apiOrder.memo || '',
    totalAmount: apiOrder.total_amount || 0,
    supplyAmount: apiOrder.supply_amount || 0,
    taxAmount: apiOrder.tax_amount || 0,
    categories: [], // Backend 구조와 다름 - items를 카테고리로 그룹화 필요
  };
}

/**
 * OrderDetailFormData → API 요청 데이터 변환
 */
function transformOrderToApi(data: OrderDetailFormData): Record<string, unknown> {
  return {
    client_id: data.partnerId ? parseInt(data.partnerId, 10) : null,
    site_name: data.siteName,
    status_code: transformToBackendStatus(data.status),
    order_type_code: transformToBackendOrderType(data.orderType),
    delivery_date: data.deliveryAddress ? undefined : undefined, // 필드 매핑 필요
    memo: data.memo,
    // items 변환은 별도 처리 필요
  };
}

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

/**
 * 발주 목록 조회
 * GET /api/v1/orders
 */
export async function getOrderList(params?: {
  size?: number;
  page?: number;
  startDate?: string;
  endDate?: string;
  status?: string;
  partnerId?: string;
  search?: string;
}): Promise<{
  success: boolean;
  data?: { items: Order[]; total: number };
  error?: string;
}> {
  try {
    const queryParams: Record<string, string> = {};

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

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

    // 상태 필터 (Frontend → Backend 변환)
    if (params?.status && params.status !== 'all') {
      queryParams.status = transformToBackendStatus(params.status as OrderStatus);
    }

    // 거래처 필터
    if (params?.partnerId && params.partnerId !== 'all') {
      queryParams.client_id = params.partnerId;
    }

    // 날짜 범위 필터
    if (params?.startDate) {
      queryParams.date_from = params.startDate;
    }
    if (params?.endDate) {
      queryParams.date_to = params.endDate;
    }

    const response = await apiClient.get<{
      success: boolean;
      data: {
        data: ApiOrder[];
        current_page: number;
        per_page: number;
        total: number;
        last_page: number;
      };
    }>('/orders', { params: queryParams });

    // API 응답 구조 처리
    const paginatedData = response.data;
    const orders = paginatedData.data || [];
    const meta = {
      total: paginatedData.total || orders.length,
      current_page: paginatedData.current_page || params?.page || 1,
      per_page: paginatedData.per_page || params?.size || 20,
    };

    const transformedOrders = orders.map(transformOrder);

    return {
      success: true,
      data: {
        items: transformedOrders,
        total: meta.total,
      },
    };
  } catch (error) {
    console.error('발주 목록 조회 오류:', error);
    return { success: false, error: '발주 목록을 불러오는데 실패했습니다.' };
  }
}

/**
 * 발주 통계 조회
 * GET /api/v1/orders/stats
 */
export async function getOrderStats(): Promise<{
  success: boolean;
  data?: OrderStats;
  error?: string;
}> {
  try {
    const response = await apiClient.get<{
      success: boolean;
      data: ApiOrderStats;
    }>('/orders/stats');

    const statsData = response.data;
    return {
      success: true,
      data: {
        total: statsData.total,
        waiting: statsData.draft,
        orderComplete: statsData.confirmed,
        deliveryScheduled: statsData.in_progress,
        deliveryComplete: statsData.completed,
      },
    };
  } catch (error) {
    console.error('발주 통계 조회 오류:', error);
    return { success: false, error: '발주 통계를 불러오는데 실패했습니다.' };
  }
}

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

/**
 * 발주 일괄 삭제
 * Backend에 batch API가 없으므로 개별 삭제 반복
 */
export async function deleteOrders(ids: string[]): Promise<{
  success: boolean;
  deletedCount?: number;
  error?: string;
}> {
  try {
    let deletedCount = 0;

    for (const id of ids) {
      try {
        await apiClient.delete(`/orders/${id}`);
        deletedCount++;
      } catch {
        // 개별 삭제 실패는 무시하고 계속 진행
        console.warn(`발주 삭제 실패: ${id}`);
      }
    }

    return { success: true, deletedCount };
  } catch (error) {
    console.error('발주 일괄 삭제 오류:', error);
    return { success: false, error: '발주 일괄 삭제에 실패했습니다.' };
  }
}

/**
 * 발주 상세 조회
 * GET /api/v1/orders/{id}
 */
export async function getOrderDetail(id: string): Promise<{
  success: boolean;
  data?: Order;
  error?: string;
}> {
  try {
    const response = await apiClient.get<{
      success: boolean;
      data: ApiOrder;
    }>(`/orders/${id}`);
    return { success: true, data: transformOrder(response.data) };
  } catch (error) {
    console.error('발주 상세 조회 오류:', error);
    return { success: false, error: '발주를 찾을 수 없습니다.' };
  }
}

/**
 * 발주 상세 조회 (전체 정보)
 * GET /api/v1/orders/{id}
 */
export async function getOrderDetailFull(id: string): Promise<{
  success: boolean;
  data?: OrderDetail;
  error?: string;
}> {
  try {
    const response = await apiClient.get<{
      success: boolean;
      data: ApiOrder;
    }>(`/orders/${id}`);
    return { success: true, data: transformOrderDetail(response.data) };
  } catch (error) {
    console.error('발주 상세 조회 오류:', error);
    return { success: false, error: '발주 상세 조회에 실패했습니다.' };
  }
}

/**
 * 발주 수정
 * PUT /api/v1/orders/{id}
 */
export async function updateOrder(
  id: string,
  data: OrderDetailFormData
): Promise<{
  success: boolean;
  error?: string;
}> {
  try {
    const apiData = transformOrderToApi(data);
    await apiClient.put(`/orders/${id}`, apiData);
    return { success: true };
  } catch (error) {
    console.error('발주 수정 오류:', error);
    return { success: false, error: '발주 수정에 실패했습니다.' };
  }
}

/**
 * 발주 복제
 * 기존 발주를 조회 후 새로 생성
 */
export async function duplicateOrder(id: string): Promise<{
  success: boolean;
  newId?: string;
  error?: string;
}> {
  try {
    // 1. 기존 발주 조회
    const existingOrderResponse = await apiClient.get<{
      success: boolean;
      data: ApiOrder;
    }>(`/orders/${id}`);
    const existingOrder = existingOrderResponse.data;

    // 2. 새 발주 생성 (order_no는 자동 생성됨)
    const newOrderData = {
      client_id: existingOrder.client_id,
      site_name: existingOrder.site_name,
      status_code: 'DRAFT', // 복제된 발주는 항상 임시저장
      order_type_code: existingOrder.order_type_code,
      delivery_date: existingOrder.delivery_date,
      memo: existingOrder.memo ? `[복제] ${existingOrder.memo}` : '[복제됨]',
      items: existingOrder.items?.map((item) => ({
        item_id: item.item_id,
        item_name: item.item_name,
        specification: item.specification,
        quantity: item.quantity,
        unit: item.unit,
        unit_price: item.unit_price,
      })),
    };

    const response = await apiClient.post<{
      success: boolean;
      data: { id: number };
    }>('/orders', newOrderData);

    return {
      success: true,
      newId: String(response.data.id),
    };
  } catch (error) {
    console.error('발주 복제 오류:', error);
    return { success: false, error: '발주 복제에 실패했습니다.' };
  }
}

/**
 * 발주 생성
 * POST /api/v1/orders
 */
export async function createOrder(data: OrderDetailFormData): Promise<{
  success: boolean;
  data?: { id: string };
  error?: string;
}> {
  try {
    const apiData = transformOrderToApi(data);
    const response = await apiClient.post<{
      success: boolean;
      data: { id: number };
    }>('/orders', apiData);

    return { success: true, data: { id: String(response.data.id) } };
  } catch (error) {
    console.error('발주 생성 오류:', error);
    return { success: false, error: '발주 생성에 실패했습니다.' };
  }
}

/**
 * 발주 상태 변경
 * PATCH /api/v1/orders/{id}/status
 */
export async function updateOrderStatus(
  id: string,
  status: OrderStatus
): Promise<{
  success: boolean;
  error?: string;
}> {
  try {
    await apiClient.patch(`/orders/${id}/status`, {
      status: transformToBackendStatus(status),
    });
    return { success: true };
  } catch (error) {
    console.error('발주 상태 변경 오류:', error);
    return { success: false, error: '발주 상태 변경에 실패했습니다.' };
  }
}

// ========================================
// 공통 코드 조회 (서버 액션용)
// ========================================

export async function getOrderStatusOptions() {
  try {
    const response = await apiClient.get<CommonCode[]>('/settings/common/order_status');
    const data = Array.isArray(response) ? response : (response as { data?: CommonCode[] }).data ?? [];
    return { success: true, data: toCommonCodeOptions(data) };
  } catch {
    return { success: false, error: '수주 상태 코드 조회 실패' };
  }
}

export async function getOrderTypeOptions() {
  try {
    const response = await apiClient.get<CommonCode[]>('/settings/common/order_type');
    const data = Array.isArray(response) ? response : (response as { data?: CommonCode[] }).data ?? [];
    return { success: true, data: toCommonCodeOptions(data) };
  } catch {
    return { success: false, error: '수주 유형 코드 조회 실패' };
  }
}