'use server';


/**
 * 작업실적 관리 Server Actions
 *
 * API Endpoints:
 * - GET /api/v1/work-results - 목록 조회
 * - GET /api/v1/work-results/stats - 통계 조회
 * - GET /api/v1/work-results/{id} - 상세 조회
 * - POST /api/v1/work-results - 등록
 * - PUT /api/v1/work-results/{id} - 수정
 * - DELETE /api/v1/work-results/{id} - 삭제
 * - PATCH /api/v1/work-results/{id}/inspection - 검사 상태 토글
 * - PATCH /api/v1/work-results/{id}/packaging - 포장 상태 토글
 */

import { executeServerAction } from '@/lib/api/execute-server-action';
import { buildApiUrl } from '@/lib/api/query-params';
import type { ProcessType } from '../WorkOrders/types';
import type {
  WorkResult,
  WorkResultStats,
  WorkResultApiPaginatedResponse,
  WorkResultStatsApi,
} from './types';
import {
  transformApiToFrontend,
  transformFrontendToApi,
  transformStatsApiToFrontend,
} from './types';

// ===== 페이지네이션 타입 =====
interface PaginationMeta {
  currentPage: number;
  lastPage: number;
  perPage: number;
  total: number;
}

// ===== 작업실적 목록 조회 =====
export async function getWorkResults(params?: {
  page?: number; size?: number; q?: string;
  processType?: ProcessType | 'all'; workOrderId?: number; workerId?: number;
  workDateFrom?: string; workDateTo?: string;
  isInspected?: boolean; isPackaged?: boolean;
}): Promise<{ success: boolean; data: WorkResult[]; pagination: PaginationMeta; error?: string }> {
  const emptyPagination = { currentPage: 1, lastPage: 1, perPage: 20, total: 0 };
  const result = await executeServerAction<WorkResultApiPaginatedResponse>({
    url: buildApiUrl('/api/v1/work-results', {
      page: params?.page,
      size: params?.size,
      q: params?.q,
      process_type: params?.processType && params.processType !== 'all' ? params.processType : undefined,
      work_order_id: params?.workOrderId,
      worker_id: params?.workerId,
      work_date_from: params?.workDateFrom,
      work_date_to: params?.workDateTo,
      is_inspected: params?.isInspected !== undefined ? (params.isInspected ? '1' : '0') : undefined,
      is_packaged: params?.isPackaged !== undefined ? (params.isPackaged ? '1' : '0') : undefined,
    }),
    errorMessage: '작업실적 목록 조회에 실패했습니다.',
  });

  if (!result.success || !result.data) {
    return { success: false, data: [], pagination: emptyPagination, error: result.error };
  }

  return {
    success: true,
    data: result.data.data.map(transformApiToFrontend),
    pagination: {
      currentPage: result.data.current_page,
      lastPage: result.data.last_page,
      perPage: result.data.per_page,
      total: result.data.total,
    },
  };
}

// ===== 작업실적 통계 조회 =====
export async function getWorkResultStats(params?: {
  workDateFrom?: string; workDateTo?: string; processType?: ProcessType | 'all';
}): Promise<{ success: boolean; data?: WorkResultStats; error?: string }> {
  const result = await executeServerAction({
    url: buildApiUrl('/api/v1/work-results/stats', {
      work_date_from: params?.workDateFrom,
      work_date_to: params?.workDateTo,
      process_type: params?.processType && params.processType !== 'all' ? params.processType : undefined,
    }),
    transform: (data: WorkResultStatsApi) => transformStatsApiToFrontend(data),
    errorMessage: '통계 조회에 실패했습니다.',
  });
  return { success: result.success, data: result.data, error: result.error };
}

// ===== 작업실적 상세 조회 =====
export async function getWorkResultById(id: string): Promise<{
  success: boolean; data?: WorkResult; error?: string;
}> {
  const result = await executeServerAction({
    url: buildApiUrl(`/api/v1/work-results/${id}`),
    transform: transformApiToFrontend,
    errorMessage: '작업실적 조회에 실패했습니다.',
  });
  return { success: result.success, data: result.data, error: result.error };
}

// ===== 작업실적 등록 =====
export async function createWorkResult(data: {
  workOrderId: number; lotNo: string; workDate: string;
  productName: string; productionQty: number; defectQty: number;
  processType?: ProcessType; specification?: string; goodQty?: number;
  workerId?: number; isInspected?: boolean; isPackaged?: boolean; memo?: string;
}): Promise<{ success: boolean; data?: WorkResult; error?: string }> {
  const apiData: Record<string, unknown> = {
    work_order_id: data.workOrderId, lot_no: data.lotNo, work_date: data.workDate,
    product_name: data.productName, production_qty: data.productionQty, defect_qty: data.defectQty,
  };
  if (data.processType) apiData.process_type = data.processType;
  if (data.specification) apiData.specification = data.specification;
  if (data.goodQty !== undefined) apiData.good_qty = data.goodQty;
  if (data.workerId) apiData.worker_id = data.workerId;
  if (data.isInspected !== undefined) apiData.is_inspected = data.isInspected;
  if (data.isPackaged !== undefined) apiData.is_packaged = data.isPackaged;
  if (data.memo) apiData.memo = data.memo;

  const result = await executeServerAction({
    url: buildApiUrl('/api/v1/work-results'),
    method: 'POST',
    body: apiData,
    transform: transformApiToFrontend,
    errorMessage: '작업실적 등록에 실패했습니다.',
  });
  return { success: result.success, data: result.data, error: result.error };
}

// ===== 작업실적 수정 =====
export async function updateWorkResult(
  id: string,
  data: Partial<WorkResult> & { workOrderId?: number; workerId?: number }
): Promise<{ success: boolean; data?: WorkResult; error?: string }> {
  const apiData = transformFrontendToApi(data);
  const result = await executeServerAction({
    url: buildApiUrl(`/api/v1/work-results/${id}`),
    method: 'PUT',
    body: apiData,
    transform: transformApiToFrontend,
    errorMessage: '작업실적 수정에 실패했습니다.',
  });
  return { success: result.success, data: result.data, error: result.error };
}

// ===== 작업실적 삭제 =====
export async function deleteWorkResult(id: string): Promise<{ success: boolean; error?: string }> {
  const result = await executeServerAction({
    url: buildApiUrl(`/api/v1/work-results/${id}`),
    method: 'DELETE',
    errorMessage: '작업실적 삭제에 실패했습니다.',
  });
  return { success: result.success, error: result.error };
}

// ===== 검사 상태 토글 =====
export async function toggleInspection(id: string): Promise<{
  success: boolean; data?: WorkResult; error?: string;
}> {
  const result = await executeServerAction({
    url: buildApiUrl(`/api/v1/work-results/${id}/inspection`),
    method: 'PATCH',
    transform: transformApiToFrontend,
    errorMessage: '검사 상태 변경에 실패했습니다.',
  });
  return { success: result.success, data: result.data, error: result.error };
}

// ===== 포장 상태 토글 =====
export async function togglePackaging(id: string): Promise<{
  success: boolean; data?: WorkResult; error?: string;
}> {
  const result = await executeServerAction({
    url: buildApiUrl(`/api/v1/work-results/${id}/packaging`),
    method: 'PATCH',
    transform: transformApiToFrontend,
    errorMessage: '포장 상태 변경에 실패했습니다.',
  });
  return { success: result.success, data: result.data, error: result.error };
}
