'use server';

import type {
  Pricing,
  PricingStats,
  PricingListResponse,
  PricingFilter,
  PricingFormData,
} from './types';
import { apiClient } from '@/lib/api';

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

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

interface ApiPricing {
  id: number;
  pricing_number: string;
  item_type: string | null;
  category: string | null;
  item_name: string;
  spec: string | null;
  order_items: ApiOrderItem[] | null;
  unit: string | null;
  division: string | null;
  vendor: string | null;
  vendor_id: number | null;
  purchase_price: number;
  margin_rate: number;
  selling_price: number;
  status: 'in_use' | 'stopped' | 'not_registered';
  created_at: string;
  updated_at: string;
}

interface ApiOrderItem {
  id: number;
  name: string;
  value: string;
}

interface ApiPricingStats {
  total: number;
  in_use: number;
  stopped: number;
  not_registered: number;
}

interface ApiVendor {
  id: number;
  name: string;
  business_no: string | null;
}

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

/**
 * API 응답 → Pricing 타입 변환
 */
function transformPricing(apiData: ApiPricing): Pricing {
  return {
    id: String(apiData.id),
    pricingNumber: apiData.pricing_number || '',
    itemType: apiData.item_type || '',
    category: apiData.category || '',
    itemName: apiData.item_name || '',
    spec: apiData.spec || '',
    orderItems: (apiData.order_items || []).map((item) => ({
      id: String(item.id),
      name: item.name || '',
      value: item.value || '',
    })),
    unit: apiData.unit || '',
    division: apiData.division || '',
    vendor: apiData.vendor || '',
    purchasePrice: apiData.purchase_price || 0,
    marginRate: apiData.margin_rate || 0,
    sellingPrice: apiData.selling_price || 0,
    status: apiData.status || 'not_registered',
    createdAt: apiData.created_at || '',
    updatedAt: apiData.updated_at || '',
  };
}

/**
 * PricingFormData → API 요청 데이터 변환
 */
function transformToApiRequest(data: Partial<PricingFormData>): Record<string, unknown> {
  const apiData: Record<string, unknown> = {};

  if (data.itemType !== undefined) apiData.item_type = data.itemType || null;
  if (data.category !== undefined) apiData.category = data.category || null;
  if (data.itemName !== undefined) apiData.item_name = data.itemName;
  if (data.spec !== undefined) apiData.spec = data.spec || null;
  if (data.unit !== undefined) apiData.unit = data.unit || null;
  if (data.division !== undefined) apiData.division = data.division || null;
  if (data.vendor !== undefined) apiData.vendor = data.vendor || null;
  if (data.purchasePrice !== undefined) apiData.purchase_price = data.purchasePrice;
  if (data.marginRate !== undefined) apiData.margin_rate = data.marginRate;
  if (data.sellingPrice !== undefined) apiData.selling_price = data.sellingPrice;
  if (data.status !== undefined) apiData.status = data.status;

  // 주문 항목 변환
  if (data.orderItems !== undefined) {
    apiData.order_items = data.orderItems.map((item) => ({
      name: item.name,
      value: item.value,
    }));
  }

  return apiData;
}

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

/**
 * 단가 목록 조회
 * GET /api/v1/pricing
 */
export async function getPricingList(filter?: PricingFilter): Promise<{
  success: boolean;
  data?: PricingListResponse;
  error?: string;
}> {
  try {
    const queryParams: Record<string, string> = {};

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

    // 필터
    if (filter?.status && filter.status !== 'all') queryParams.status = filter.status;
    if (filter?.itemType && filter.itemType !== 'all') queryParams.item_type = filter.itemType;
    if (filter?.category && filter.category !== 'all') queryParams.category = filter.category;
    if (filter?.division && filter.division !== 'all') queryParams.division = filter.division;

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

    // 정렬
    if (filter?.sortBy) {
      const sortMap: Record<string, { field: string; dir: string }> = {
        latest: { field: 'created_at', dir: 'desc' },
        oldest: { field: 'created_at', dir: 'asc' },
        itemNameAsc: { field: 'item_name', dir: 'asc' },
        itemNameDesc: { field: 'item_name', dir: 'desc' },
        priceAsc: { field: 'selling_price', dir: 'asc' },
        priceDesc: { field: 'selling_price', dir: 'desc' },
        price_high: { field: 'selling_price', dir: 'desc' },
        price_low: { field: 'selling_price', dir: 'asc' },
      };
      const sort = sortMap[filter.sortBy];
      if (sort) {
        queryParams.sort_by = sort.field;
        queryParams.sort_dir = sort.dir;
      }
    }

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

    const items = (response.data || []).map(transformPricing);

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

/**
 * 단가 통계 조회
 * GET /api/v1/pricing/stats
 */
export async function getPricingStats(): Promise<{
  success: boolean;
  data?: PricingStats;
  error?: string;
}> {
  try {
    const response = await apiClient.get<ApiPricingStats>('/pricing/stats');

    return {
      success: true,
      data: {
        total: response.total || 0,
        inUse: response.in_use || 0,
        notRegistered: response.not_registered || 0,
      },
    };
  } catch (error) {
    console.error('단가 통계 조회 오류:', error);
    return { success: false, error: '통계를 불러오는데 실패했습니다.' };
  }
}

/**
 * 단가 상세 조회
 * GET /api/v1/pricing/{id}
 */
export async function getPricingDetail(id: string): Promise<{
  success: boolean;
  data?: Pricing;
  error?: string;
}> {
  try {
    const response = await apiClient.get<ApiPricing>(`/pricing/${id}`);
    return { success: true, data: transformPricing(response) };
  } catch (error) {
    console.error('단가 상세 조회 오류:', error);
    return { success: false, error: '단가 정보를 찾을 수 없습니다.' };
  }
}

/**
 * 단가 등록
 * POST /api/v1/pricing
 */
export async function createPricing(data: PricingFormData): Promise<{
  success: boolean;
  data?: Pricing;
  error?: string;
}> {
  try {
    const apiData = transformToApiRequest(data);
    const response = await apiClient.post<ApiPricing>('/pricing', apiData);
    return { success: true, data: transformPricing(response) };
  } catch (error) {
    console.error('단가 등록 오류:', error);
    return { success: false, error: '단가 등록에 실패했습니다.' };
  }
}

/**
 * 단가 수정
 * PUT /api/v1/pricing/{id}
 */
export async function updatePricing(
  id: string,
  data: Partial<PricingFormData>
): Promise<{
  success: boolean;
  data?: Pricing;
  error?: string;
}> {
  try {
    const apiData = transformToApiRequest(data);
    const response = await apiClient.put<ApiPricing>(`/pricing/${id}`, apiData);
    return { success: true, data: transformPricing(response) };
  } catch (error) {
    console.error('단가 수정 오류:', error);
    return { success: false, error: '단가 수정에 실패했습니다.' };
  }
}

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

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

/**
 * 거래처(벤더) 목록 조회
 * GET /api/v1/clients (거래처 API 재사용)
 */
export async function getVendorList(): Promise<{
  success: boolean;
  data?: { id: string; name: string }[];
  error?: string;
}> {
  try {
    const response = await apiClient.get<{
      data: ApiVendor[];
    }>('/clients', { params: { per_page: '100' } });

    const vendors = (response.data || []).map((v) => ({
      id: String(v.id),
      name: v.name || '',
    }));

    return { success: true, data: vendors };
  } catch (error) {
    console.error('거래처 목록 조회 오류:', error);
    return { success: false, error: '거래처 목록을 불러오는데 실패했습니다.' };
  }
}

/**
 * 단가 확정
 * POST /api/v1/pricing/{id}/finalize
 */
export async function finalizePricing(id: string): Promise<{
  success: boolean;
  data?: Pricing;
  error?: string;
}> {
  try {
    const response = await apiClient.post<ApiPricing>(`/pricing/${id}/finalize`);
    return { success: true, data: transformPricing(response) };
  } catch (error) {
    console.error('단가 확정 오류:', error);
    return { success: false, error: '단가 확정에 실패했습니다.' };
  }
}

/**
 * 단가 변경이력 조회
 * GET /api/v1/pricing/{id}/revisions
 */
export async function getPricingRevisions(id: string): Promise<{
  success: boolean;
  data?: Pricing[];
  error?: string;
}> {
  try {
    const response = await apiClient.get<{ data: ApiPricing[] }>(`/pricing/${id}/revisions`);
    const revisions = (response.data || []).map(transformPricing);
    return { success: true, data: revisions };
  } catch (error) {
    console.error('단가 변경이력 조회 오류:', error);
    return { success: false, error: '변경이력을 불러오는데 실패했습니다.' };
  }
}