'use server';


import { isNextRedirectError } from '@/lib/utils/redirect-error';
/**
 * 검사 관리 Server Actions
 * API 연동 완료 (2025-12-26)
 * fetch-wrapper 마이그레이션 완료 (2025-12-30)
 *
 * API Endpoints:
 * - GET /api/v1/inspections - 목록 조회
 * - GET /api/v1/inspections/stats - 통계 조회
 * - GET /api/v1/inspections/{id} - 상세 조회
 * - POST /api/v1/inspections - 등록
 * - PUT /api/v1/inspections/{id} - 수정
 * - DELETE /api/v1/inspections/{id} - 삭제
 * - PATCH /api/v1/inspections/{id}/complete - 검사 완료 처리
 */

import { serverFetch } from '@/lib/api/fetch-wrapper';
import type {
  Inspection,
  InspectionStats,
  InspectionType,
  InspectionStatus,
  InspectionItem,
} from './types';

// ===== API 타입 =====
interface InspectionApiItem {
  id: number;
  inspection_no: string;
  inspection_type: 'IQC' | 'PQC' | 'FQC';
  request_date: string;
  inspection_date?: string;
  item_name: string;
  lot_no: string;
  process_name: string;
  quantity: number;
  unit: string;
  status: 'waiting' | 'in_progress' | 'completed';
  result?: 'pass' | 'fail';
  inspector_id?: number;
  inspector?: { id: number; name: string };
  items?: Array<{
    id: string;
    name: string;
    type: 'quality' | 'measurement';
    spec: string;
    unit?: string;
    result?: string;
    measured_value?: number;
    judgment?: 'pass' | 'fail';
  }>;
  remarks?: string;
  opinion?: string;
  attachments?: Array<{
    id: string;
    file_name: string;
    file_url: string;
    file_type: string;
    uploaded_at: string;
  }>;
  created_at: string;
  updated_at: string;
}

interface InspectionApiPaginatedResponse {
  items: InspectionApiItem[];
  current_page: number;
  last_page: number;
  per_page: number;
  total: number;
}

interface InspectionStatsApi {
  waiting_count: number;
  in_progress_count: number;
  completed_count: number;
  defect_rate: number;
}

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

// ===== 상태 변환 =====
function mapApiStatus(status: InspectionApiItem['status']): InspectionStatus {
  switch (status) {
    case 'waiting':
      return '대기';
    case 'in_progress':
      return '진행중';
    case 'completed':
      return '완료';
    default:
      return '대기';
  }
}

function mapFrontendStatus(status: InspectionStatus): string {
  switch (status) {
    case '대기':
      return 'waiting';
    case '진행중':
      return 'in_progress';
    case '완료':
      return 'completed';
    default:
      return 'waiting';
  }
}

// ===== API → Frontend 변환 =====
function transformApiToFrontend(api: InspectionApiItem): Inspection {
  const items: InspectionItem[] = (api.items || []).map((item) => {
    if (item.type === 'measurement') {
      return {
        id: item.id,
        name: item.name,
        type: 'measurement' as const,
        spec: item.spec,
        unit: item.unit || '',
        measuredValue: item.measured_value,
        judgment: item.judgment === 'pass' ? '적합' : item.judgment === 'fail' ? '부적합' : undefined,
      };
    }
    return {
      id: item.id,
      name: item.name,
      type: 'quality' as const,
      spec: item.spec,
      result: item.result === 'good' ? '양호' : item.result === 'bad' ? '불량' : undefined,
      judgment: item.judgment === 'pass' ? '적합' : item.judgment === 'fail' ? '부적합' : undefined,
    };
  });

  return {
    id: String(api.id),
    inspectionNo: api.inspection_no,
    inspectionType: api.inspection_type,
    requestDate: api.request_date,
    inspectionDate: api.inspection_date,
    itemName: api.item_name,
    lotNo: api.lot_no,
    processName: api.process_name,
    quantity: api.quantity,
    unit: api.unit,
    status: mapApiStatus(api.status),
    result: api.result === 'pass' ? '합격' : api.result === 'fail' ? '불합격' : undefined,
    inspector: api.inspector?.name,
    items,
    remarks: api.remarks,
    opinion: api.opinion,
    attachments: api.attachments?.map((att) => ({
      id: att.id,
      fileName: att.file_name,
      fileUrl: att.file_url,
      fileType: att.file_type,
      uploadedAt: att.uploaded_at,
    })),
  };
}

// ===== 검사 목록 조회 =====
export async function getInspections(params?: {
  page?: number;
  size?: number;
  q?: string;
  status?: InspectionStatus | '전체';
  inspectionType?: InspectionType;
  dateFrom?: string;
  dateTo?: string;
}): Promise<{
  success: boolean;
  data: Inspection[];
  pagination: PaginationMeta;
  error?: string;
  __authError?: boolean;
}> {
  try {
    const searchParams = new URLSearchParams();

    if (params?.page) searchParams.set('page', String(params.page));
    if (params?.size) searchParams.set('per_page', String(params.size));
    if (params?.q) searchParams.set('q', params.q);
    if (params?.status && params.status !== '전체') {
      searchParams.set('status', mapFrontendStatus(params.status));
    }
    if (params?.inspectionType) {
      searchParams.set('inspection_type', params.inspectionType);
    }
    if (params?.dateFrom) searchParams.set('date_from', params.dateFrom);
    if (params?.dateTo) searchParams.set('date_to', params.dateTo);

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

    console.log('[InspectionActions] GET inspections:', url);

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

    if (error) {
      return {
        success: false,
        data: [],
        pagination: { currentPage: 1, lastPage: 1, perPage: 20, total: 0 },
        error: error.message,
        __authError: error.code === 'UNAUTHORIZED',
      };
    }

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

    if (!response.ok) {
      console.warn('[InspectionActions] GET inspections 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: InspectionApiPaginatedResponse = result.data || {
      items: [],
      current_page: 1,
      last_page: 1,
      per_page: 20,
      total: 0,
    };

    return {
      success: true,
      data: paginatedData.items.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('[InspectionActions] getInspections error:', error);
    return {
      success: false,
      data: [],
      pagination: { currentPage: 1, lastPage: 1, perPage: 20, total: 0 },
      error: '서버 오류가 발생했습니다.',
    };
  }
}

// ===== 검사 통계 조회 =====
export async function getInspectionStats(params?: {
  dateFrom?: string;
  dateTo?: string;
  inspectionType?: InspectionType;
}): Promise<{
  success: boolean;
  data?: InspectionStats;
  error?: string;
  __authError?: boolean;
}> {
  try {
    const searchParams = new URLSearchParams();

    if (params?.dateFrom) searchParams.set('date_from', params.dateFrom);
    if (params?.dateTo) searchParams.set('date_to', params.dateTo);
    if (params?.inspectionType) {
      searchParams.set('inspection_type', params.inspectionType);
    }

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

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

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

    if (error) {
      return {
        success: false,
        error: error.message,
        __authError: error.code === 'UNAUTHORIZED',
      };
    }

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

    if (!response.ok) {
      console.warn('[InspectionActions] 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: InspectionStatsApi = result.data;

    return {
      success: true,
      data: {
        waitingCount: statsApi.waiting_count,
        inProgressCount: statsApi.in_progress_count,
        completedCount: statsApi.completed_count,
        defectRate: statsApi.defect_rate,
      },
    };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[InspectionActions] getInspectionStats error:', error);
    return {
      success: false,
      error: '서버 오류가 발생했습니다.',
    };
  }
}

// ===== 검사 상세 조회 =====
export async function getInspectionById(id: string): Promise<{
  success: boolean;
  data?: Inspection;
  error?: string;
  __authError?: boolean;
}> {
  try {
    const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/inspections/${id}`;

    console.log('[InspectionActions] GET inspection:', url);

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

    if (error) {
      return {
        success: false,
        error: error.message,
        __authError: error.code === 'UNAUTHORIZED',
      };
    }

    if (!response) {
      return {
        success: false,
        error: '검사 조회에 실패했습니다.',
      };
    }

    if (!response.ok) {
      console.error('[InspectionActions] GET inspection 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('[InspectionActions] getInspectionById error:', error);
    return {
      success: false,
      error: '서버 오류가 발생했습니다.',
    };
  }
}

// ===== 검사 등록 =====
export async function createInspection(data: {
  inspectionType: InspectionType;
  lotNo: string;
  itemName: string;
  processName: string;
  quantity: number;
  unit: string;
  inspectorId?: number;
  remarks?: string;
  items?: InspectionItem[];
}): Promise<{
  success: boolean;
  data?: Inspection;
  error?: string;
  __authError?: boolean;
}> {
  try {
    const apiData: Record<string, unknown> = {
      inspection_type: data.inspectionType,
      lot_no: data.lotNo,
      item_name: data.itemName,
      process_name: data.processName,
      quantity: data.quantity,
      unit: data.unit,
    };

    if (data.inspectorId) apiData.inspector_id = data.inspectorId;
    if (data.remarks) apiData.remarks = data.remarks;
    if (data.items && data.items.length > 0) {
      apiData.items = data.items.map((item) => ({
        name: item.name,
        type: item.type,
        spec: item.spec,
        unit: item.type === 'measurement' ? (item as { unit?: string }).unit : undefined,
      }));
    }

    console.log('[InspectionActions] POST inspection request:', apiData);

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

    if (error) {
      return {
        success: false,
        error: error.message,
        __authError: error.code === 'UNAUTHORIZED',
      };
    }

    if (!response) {
      return {
        success: false,
        error: '검사 등록에 실패했습니다.',
      };
    }

    const result = await response.json();
    console.log('[InspectionActions] POST 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('[InspectionActions] createInspection error:', error);
    return {
      success: false,
      error: '서버 오류가 발생했습니다.',
    };
  }
}

// ===== 검사 수정 =====
export async function updateInspection(
  id: string,
  data: {
    items?: InspectionItem[];
    result?: '합격' | '불합격';
    remarks?: string;
    opinion?: string;
  }
): Promise<{
  success: boolean;
  data?: Inspection;
  error?: string;
  __authError?: boolean;
}> {
  try {
    const apiData: Record<string, unknown> = {};

    if (data.items) {
      apiData.items = data.items.map((item) => {
        if (item.type === 'measurement') {
          const measurementItem = item as { measuredValue?: number; judgment?: string };
          return {
            id: item.id,
            measured_value: measurementItem.measuredValue,
            judgment: measurementItem.judgment === '적합' ? 'pass' : 'fail',
          };
        }
        const qualityItem = item as { result?: string; judgment?: string };
        return {
          id: item.id,
          result: qualityItem.result === '양호' ? 'good' : 'bad',
          judgment: qualityItem.judgment === '적합' ? 'pass' : 'fail',
        };
      });
    }

    if (data.result) {
      apiData.result = data.result === '합격' ? 'pass' : 'fail';
    }
    if (data.remarks !== undefined) apiData.remarks = data.remarks;
    if (data.opinion !== undefined) apiData.opinion = data.opinion;

    console.log('[InspectionActions] PUT inspection request:', apiData);

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

    if (error) {
      return {
        success: false,
        error: error.message,
        __authError: error.code === 'UNAUTHORIZED',
      };
    }

    if (!response) {
      return {
        success: false,
        error: '검사 수정에 실패했습니다.',
      };
    }

    const result = await response.json();
    console.log('[InspectionActions] PUT 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('[InspectionActions] updateInspection error:', error);
    return {
      success: false,
      error: '서버 오류가 발생했습니다.',
    };
  }
}

// ===== 검사 삭제 =====
export async function deleteInspection(id: string): Promise<{
  success: boolean;
  error?: string;
  __authError?: boolean;
}> {
  try {
    const { response, error } = await serverFetch(
      `${process.env.NEXT_PUBLIC_API_URL}/api/v1/inspections/${id}`,
      {
        method: 'DELETE',
      }
    );

    if (error) {
      return {
        success: false,
        error: error.message,
        __authError: error.code === 'UNAUTHORIZED',
      };
    }

    if (!response) {
      return {
        success: false,
        error: '검사 삭제에 실패했습니다.',
      };
    }

    const result = await response.json();
    console.log('[InspectionActions] DELETE inspection 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('[InspectionActions] deleteInspection error:', error);
    return {
      success: false,
      error: '서버 오류가 발생했습니다.',
    };
  }
}

// ===== 검사 완료 처리 =====
export async function completeInspection(
  id: string,
  data: {
    result: '합격' | '불합격';
    opinion?: string;
  }
): Promise<{
  success: boolean;
  data?: Inspection;
  error?: string;
  __authError?: boolean;
}> {
  try {
    const apiData = {
      result: data.result === '합격' ? 'pass' : 'fail',
      opinion: data.opinion,
    };

    console.log('[InspectionActions] PATCH complete request:', apiData);

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

    if (error) {
      return {
        success: false,
        error: error.message,
        __authError: error.code === 'UNAUTHORIZED',
      };
    }

    if (!response) {
      return {
        success: false,
        error: '검사 완료 처리에 실패했습니다.',
      };
    }

    const result = await response.json();
    console.log('[InspectionActions] PATCH complete 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('[InspectionActions] completeInspection error:', error);
    return {
      success: false,
      error: '서버 오류가 발생했습니다.',
    };
  }
}