'use server';

import type {
  Labor,
  LaborListParams,
  LaborFormData,
  LaborStats,
} from './types';
import { apiClient } from '@/lib/api';

/**
 * 시공관리 - 노임관리 Server Actions
 * 표준화된 apiClient 사용 버전
 */

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

interface ApiLabor {
  id: number;
  labor_number: string;
  category: '가로' | '세로할증';
  min_m: number;
  max_m: number;
  labor_price: number | null;
  status: '사용' | '중지';
  is_active: boolean;
  created_at: string;
  updated_at: string;
}

interface ApiLaborStats {
  total: number;
  active: number;
}

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

/**
 * API 응답 → Labor 타입 변환
 */
function transformLabor(apiData: ApiLabor): Labor {
  return {
    id: String(apiData.id),
    laborNumber: apiData.labor_number || '',
    category: apiData.category || '가로',
    minM: apiData.min_m || 0,
    maxM: apiData.max_m || 0,
    laborPrice: apiData.labor_price,
    status: apiData.status || '사용',
    createdAt: apiData.created_at || '',
    updatedAt: apiData.updated_at || '',
  };
}

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

  if (data.laborNumber !== undefined) apiData.labor_number = data.laborNumber;
  if (data.category !== undefined) apiData.category = data.category;
  if (data.minM !== undefined) apiData.min_m = data.minM;
  if (data.maxM !== undefined) apiData.max_m = data.maxM;
  if (data.laborPrice !== undefined) apiData.labor_price = data.laborPrice;
  if (data.status !== undefined) apiData.status = data.status;

  return apiData;
}

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

/**
 * 노임 목록 조회
 * GET /api/v1/labor
 */
export async function getLaborList(params: LaborListParams = {}): Promise<{
  success: boolean;
  data?: Labor[];
  total?: number;
  error?: string;
}> {
  try {
    const queryParams: Record<string, string> = {};

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

    // 필터
    if (params.category && params.category !== 'all') queryParams.category = params.category;
    if (params.status && params.status !== 'all') queryParams.status = params.status;

    // 날짜 필터
    if (params.startDate) queryParams.start_date = params.startDate;
    if (params.endDate) queryParams.end_date = params.endDate;

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

    // 정렬
    if (params.sortOrder === '등록순') {
      queryParams.sort_by = 'created_at';
      queryParams.sort_dir = 'asc';
    } else {
      // 기본: 최신순
      queryParams.sort_by = 'created_at';
      queryParams.sort_dir = 'desc';
    }

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

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

    return {
      success: true,
      data: items,
      total: response.total || 0,
    };
  } catch (error) {
    console.error('노임 목록 조회 실패:', error);
    return { success: false, error: '노임 목록을 불러오는데 실패했습니다.' };
  }
}

/**
 * 노임 통계 조회
 * GET /api/v1/labor/stats
 */
export async function getLaborStats(): Promise<{
  success: boolean;
  data?: LaborStats;
  error?: string;
}> {
  try {
    const response = await apiClient.get<ApiLaborStats>('/labor/stats');

    return {
      success: true,
      data: {
        total: response.total || 0,
        active: response.active || 0,
      },
    };
  } catch (error) {
    console.error('노임 통계 조회 실패:', error);
    return { success: false, error: '노임 통계를 불러오는데 실패했습니다.' };
  }
}

/**
 * 노임 상세 조회
 * GET /api/v1/labor/{id}
 */
export async function getLabor(id: string): Promise<{
  success: boolean;
  data?: Labor;
  error?: string;
}> {
  try {
    const response = await apiClient.get<ApiLabor>(`/labor/${id}`);
    return { success: true, data: transformLabor(response) };
  } catch (error) {
    console.error('노임 상세 조회 실패:', error);
    return { success: false, error: '노임 정보를 찾을 수 없습니다.' };
  }
}

/**
 * 노임 등록
 * POST /api/v1/labor
 */
export async function createLabor(data: LaborFormData): Promise<{
  success: boolean;
  data?: Labor;
  error?: string;
}> {
  try {
    const apiData = transformToApiRequest(data);
    const response = await apiClient.post<ApiLabor>('/labor', apiData);
    return { success: true, data: transformLabor(response) };
  } catch (error) {
    console.error('노임 등록 실패:', error);
    return { success: false, error: '노임 등록에 실패했습니다.' };
  }
}

/**
 * 노임 수정
 * PUT /api/v1/labor/{id}
 */
export async function updateLabor(
  id: string,
  data: LaborFormData
): Promise<{
  success: boolean;
  data?: Labor;
  error?: string;
}> {
  try {
    const apiData = transformToApiRequest(data);
    const response = await apiClient.put<ApiLabor>(`/labor/${id}`, apiData);
    return { success: true, data: transformLabor(response) };
  } catch (error) {
    console.error('노임 수정 실패:', error);
    return { success: false, error: '노임 수정에 실패했습니다.' };
  }
}

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

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