'use server';


import { isNextRedirectError } from '@/lib/utils/redirect-error';
/**
 * 작업실적 관리 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 { serverFetch } from '@/lib/api/fetch-wrapper';
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;
}> {
  try {
    const searchParams = new URLSearchParams();

    if (params?.page) searchParams.set('page', String(params.page));
    if (params?.size) searchParams.set('size', String(params.size));
    if (params?.q) searchParams.set('q', params.q);
    if (params?.processType && params.processType !== 'all') {
      searchParams.set('process_type', params.processType);
    }
    if (params?.workOrderId) searchParams.set('work_order_id', String(params.workOrderId));
    if (params?.workerId) searchParams.set('worker_id', String(params.workerId));
    if (params?.workDateFrom) searchParams.set('work_date_from', params.workDateFrom);
    if (params?.workDateTo) searchParams.set('work_date_to', params.workDateTo);
    if (params?.isInspected !== undefined) {
      searchParams.set('is_inspected', params.isInspected ? '1' : '0');
    }
    if (params?.isPackaged !== undefined) {
      searchParams.set('is_packaged', params.isPackaged ? '1' : '0');
    }

    const queryString = searchParams.toString();
    const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/work-results${queryString ? `?${queryString}` : ''}`;

    console.log('[WorkResultActions] GET work-results:', url);

    const { response, error } = await serverFetch(url, {
      method: 'GET',
    });

    if (error || !response) {
      console.warn('[WorkResultActions] GET work-results error:', error?.message);
      return {
        success: false,
        data: [],
        pagination: { currentPage: 1, lastPage: 1, perPage: 20, total: 0 },
        error: error?.message || '서버 오류가 발생했습니다.',
      };
    }

    if (!response.ok) {
      console.warn('[WorkResultActions] GET work-results error:', response.status);
      return {
        success: false,
        data: [],
        pagination: { currentPage: 1, lastPage: 1, perPage: 20, total: 0 },
        error: `API 오류: ${response.status}`,
      };
    }

    const result = await response.json();

    if (!result.success) {
      return {
        success: false,
        data: [],
        pagination: { currentPage: 1, lastPage: 1, perPage: 20, total: 0 },
        error: result.message || '작업실적 목록 조회에 실패했습니다.',
      };
    }

    const paginatedData: WorkResultApiPaginatedResponse = result.data || {
      data: [],
      current_page: 1,
      last_page: 1,
      per_page: 20,
      total: 0,
    };

    return {
      success: true,
      data: paginatedData.data.map(transformApiToFrontend),
      pagination: {
        currentPage: paginatedData.current_page,
        lastPage: paginatedData.last_page,
        perPage: paginatedData.per_page,
        total: paginatedData.total,
      },
    };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[WorkResultActions] getWorkResults error:', error);
    return {
      success: false,
      data: [],
      pagination: { currentPage: 1, lastPage: 1, perPage: 20, total: 0 },
      error: '서버 오류가 발생했습니다.',
    };
  }
}

// ===== 작업실적 통계 조회 =====
export async function getWorkResultStats(params?: {
  workDateFrom?: string;
  workDateTo?: string;
  processType?: ProcessType | 'all';
}): Promise<{
  success: boolean;
  data?: WorkResultStats;
  error?: string;
}> {
  try {
    const searchParams = new URLSearchParams();

    if (params?.workDateFrom) searchParams.set('work_date_from', params.workDateFrom);
    if (params?.workDateTo) searchParams.set('work_date_to', params.workDateTo);
    if (params?.processType && params.processType !== 'all') {
      searchParams.set('process_type', params.processType);
    }

    const queryString = searchParams.toString();
    const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/work-results/stats${queryString ? `?${queryString}` : ''}`;

    console.log('[WorkResultActions] GET stats:', url);

    const { response, error } = await serverFetch(url, {
      method: 'GET',
    });

    if (error || !response) {
      console.warn('[WorkResultActions] GET stats error:', error?.message);
      return {
        success: false,
        error: error?.message || '서버 오류가 발생했습니다.',
      };
    }

    if (!response.ok) {
      console.warn('[WorkResultActions] GET stats error:', response.status);
      return {
        success: false,
        error: `API 오류: ${response.status}`,
      };
    }

    const result = await response.json();

    if (!result.success) {
      return {
        success: false,
        error: result.message || '통계 조회에 실패했습니다.',
      };
    }

    const statsApi: WorkResultStatsApi = result.data;

    return {
      success: true,
      data: transformStatsApiToFrontend(statsApi),
    };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[WorkResultActions] getWorkResultStats error:', error);
    return {
      success: false,
      error: '서버 오류가 발생했습니다.',
    };
  }
}

// ===== 작업실적 상세 조회 =====
export async function getWorkResultById(id: string): Promise<{
  success: boolean;
  data?: WorkResult;
  error?: string;
}> {
  try {
    const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/work-results/${id}`;

    console.log('[WorkResultActions] GET work-result:', url);

    const { response, error } = await serverFetch(url, {
      method: 'GET',
    });

    if (error || !response) {
      console.error('[WorkResultActions] GET work-result error:', error?.message);
      return {
        success: false,
        error: error?.message || '서버 오류가 발생했습니다.',
      };
    }

    if (!response.ok) {
      console.error('[WorkResultActions] GET work-result error:', response.status);
      return {
        success: false,
        error: `API 오류: ${response.status}`,
      };
    }

    const result = await response.json();

    if (!result.success || !result.data) {
      return {
        success: false,
        error: result.message || '작업실적 조회에 실패했습니다.',
      };
    }

    return {
      success: true,
      data: transformApiToFrontend(result.data),
    };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[WorkResultActions] getWorkResultById error:', error);
    return {
      success: false,
      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;
}> {
  try {
    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;

    console.log('[WorkResultActions] POST work-result request:', apiData);

    const { response, error } = await serverFetch(
      `${process.env.NEXT_PUBLIC_API_URL}/api/v1/work-results`,
      {
        method: 'POST',
        body: JSON.stringify(apiData),
      }
    );

    if (error || !response) {
      console.error('[WorkResultActions] POST work-result error:', error?.message);
      return {
        success: false,
        error: error?.message || '서버 오류가 발생했습니다.',
      };
    }

    const result = await response.json();
    console.log('[WorkResultActions] POST work-result response:', result);

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

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

// ===== 작업실적 수정 =====
export async function updateWorkResult(
  id: string,
  data: Partial<WorkResult> & { workOrderId?: number; workerId?: number }
): Promise<{
  success: boolean;
  data?: WorkResult;
  error?: string;
}> {
  try {
    const apiData = transformFrontendToApi(data);

    console.log('[WorkResultActions] PUT work-result request:', apiData);

    const { response, error } = await serverFetch(
      `${process.env.NEXT_PUBLIC_API_URL}/api/v1/work-results/${id}`,
      {
        method: 'PUT',
        body: JSON.stringify(apiData),
      }
    );

    if (error || !response) {
      console.error('[WorkResultActions] PUT work-result error:', error?.message);
      return {
        success: false,
        error: error?.message || '서버 오류가 발생했습니다.',
      };
    }

    const result = await response.json();
    console.log('[WorkResultActions] PUT work-result response:', result);

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

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

// ===== 작업실적 삭제 =====
export async function deleteWorkResult(id: string): Promise<{
  success: boolean;
  error?: string;
}> {
  try {
    const { response, error } = await serverFetch(
      `${process.env.NEXT_PUBLIC_API_URL}/api/v1/work-results/${id}`,
      {
        method: 'DELETE',
      }
    );

    if (error || !response) {
      console.error('[WorkResultActions] DELETE work-result error:', error?.message);
      return {
        success: false,
        error: error?.message || '서버 오류가 발생했습니다.',
      };
    }

    const result = await response.json();
    console.log('[WorkResultActions] DELETE work-result response:', result);

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

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

// ===== 검사 상태 토글 =====
export async function toggleInspection(id: string): Promise<{
  success: boolean;
  data?: WorkResult;
  error?: string;
}> {
  try {
    console.log('[WorkResultActions] PATCH inspection toggle:', id);

    const { response, error } = await serverFetch(
      `${process.env.NEXT_PUBLIC_API_URL}/api/v1/work-results/${id}/inspection`,
      {
        method: 'PATCH',
      }
    );

    if (error || !response) {
      console.error('[WorkResultActions] PATCH inspection error:', error?.message);
      return {
        success: false,
        error: error?.message || '서버 오류가 발생했습니다.',
      };
    }

    const result = await response.json();
    console.log('[WorkResultActions] PATCH inspection response:', result);

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

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

// ===== 포장 상태 토글 =====
export async function togglePackaging(id: string): Promise<{
  success: boolean;
  data?: WorkResult;
  error?: string;
}> {
  try {
    console.log('[WorkResultActions] PATCH packaging toggle:', id);

    const { response, error } = await serverFetch(
      `${process.env.NEXT_PUBLIC_API_URL}/api/v1/work-results/${id}/packaging`,
      {
        method: 'PATCH',
      }
    );

    if (error || !response) {
      console.error('[WorkResultActions] PATCH packaging error:', error?.message);
      return {
        success: false,
        error: error?.message || '서버 오류가 발생했습니다.',
      };
    }

    const result = await response.json();
    console.log('[WorkResultActions] PATCH packaging response:', result);

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

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