/**
 * 생산 현황판 서버 액션
 * API 연동 완료 (2025-12-26)
 * serverFetch 마이그레이션 (2025-12-30)
 * 공정 기반 동적 탭 전환 (2025-01-15)
 */

'use server';


import { isNextRedirectError } from '@/lib/utils/redirect-error';
import { serverFetch } from '@/lib/api/fetch-wrapper';
import type { WorkOrder, WorkerStatus, DashboardStats, ProcessOption } from './types';

// ===== API 타입 =====
interface WorkOrderApiItem {
  id: number;
  work_order_no: string;
  project_name: string | null;
  process_id: number | null;
  process?: {
    id: number;
    process_code: string;
    process_name: string;
  };
  status: 'unassigned' | 'pending' | 'waiting' | 'in_progress' | 'completed' | 'shipped';
  scheduled_date: string | null;
  memo: string | null;
  created_at: string;
  sales_order?: {
    id: number;
    order_no: string;
    client_id?: number;
    client_name?: string;
    client?: { id: number; name: string };
  };
  assignee?: { id: number; name: string };
  items?: { id: number; item_name: string; quantity: number }[];
}

// ===== 상태 변환 =====
function mapApiStatus(status: WorkOrderApiItem['status']): 'waiting' | 'inProgress' | 'completed' {
  switch (status) {
    case 'in_progress':
      return 'inProgress';
    case 'completed':
    case 'shipped':
      return 'completed';
    default:
      return 'waiting';
  }
}

// ===== API → WorkOrder 변환 =====
function transformToProductionFormat(api: WorkOrderApiItem): WorkOrder {
  const totalQuantity = (api.items || []).reduce((sum, item) => sum + item.quantity, 0);
  const productName = api.items?.[0]?.item_name || '-';

  // 납기일 계산 (지연 여부)
  const dueDate = api.scheduled_date || '';
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  const due = dueDate ? new Date(dueDate) : null;
  const isDelayed = due ? due < today && api.status !== 'completed' && api.status !== 'shipped' : false;
  const delayDays = due && isDelayed
    ? Math.ceil((today.getTime() - due.getTime()) / (1000 * 60 * 60 * 24))
    : undefined;

  // 긴급 여부 (3일 이내 납기)
  const isUrgent = due
    ? due.getTime() - today.getTime() <= 3 * 24 * 60 * 60 * 1000 && due.getTime() >= today.getTime()
    : false;

  return {
    id: String(api.id),
    orderNo: api.work_order_no,
    productName,
    processCode: api.process?.process_code || '-',
    processName: api.process?.process_name || '-',
    client: api.sales_order?.client_name || api.sales_order?.client?.name || '-',
    projectName: api.project_name || '-',
    assignees: api.assignee ? [api.assignee.name] : [],
    quantity: totalQuantity,
    dueDate,
    priority: isUrgent ? 1 : 5,
    status: mapApiStatus(api.status),
    isUrgent,
    isDelayed,
    delayDays,
    instruction: api.memo || undefined,
    createdAt: api.created_at,
  };
}

// ===== 공정 옵션 목록 조회 =====
export async function getProcessOptions(): Promise<{
  success: boolean;
  data: ProcessOption[];
  error?: string;
}> {
  try {
    const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/processes/options`;
    console.log('[ProductionDashboardActions] GET processes:', url);

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

    if (error || !response) {
      console.warn('[ProductionDashboardActions] GET processes error:', error?.message);
      return {
        success: false,
        data: [],
        error: error?.message || '공정 목록 조회에 실패했습니다.',
      };
    }

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

    const result = await response.json();

    if (!result.success) {
      return {
        success: false,
        data: [],
        error: result.message || '공정 목록 조회에 실패했습니다.',
      };
    }

    // API 응답: { success, data: [{ id, process_code, process_name, process_type, department }] }
    const processes: ProcessOption[] = (result.data || []).map((p: {
      id: number;
      process_code: string;
      process_name: string;
      process_type?: string;
      department?: string;
    }) => ({
      id: p.id,
      code: p.process_code,
      name: p.process_name,
      type: p.process_type,
      department: p.department,
    }));

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

// ===== 대시보드 데이터 조회 =====
export async function getDashboardData(processCode?: string): Promise<{
  success: boolean;
  workOrders: WorkOrder[];
  workerStatus: WorkerStatus[];
  stats: DashboardStats;
  error?: string;
}> {
  const emptyResult = {
    success: false,
    workOrders: [] as WorkOrder[],
    workerStatus: [] as WorkerStatus[],
    stats: { total: 0, waiting: 0, inProgress: 0, completed: 0, urgent: 0, delayed: 0 },
  };

  try {
    // 작업지시 목록 조회
    const params = new URLSearchParams({ per_page: '100' });
    if (processCode && processCode !== 'all') {
      params.set('process_code', processCode);
    }

    const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/work-orders?${params.toString()}`;
    console.log('[ProductionDashboardActions] GET:', url);

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

    // serverFetch handles 401 with redirect, so we only check for other errors
    if (error || !response) {
      console.warn('[ProductionDashboardActions] GET error:', error?.message);
      return {
        ...emptyResult,
        error: error?.message || '데이터 조회에 실패했습니다.',
      };
    }

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

    const result = await response.json();

    if (!result.success) {
      return {
        ...emptyResult,
        error: result.message || '데이터 조회에 실패했습니다.',
      };
    }

    const apiData: WorkOrderApiItem[] = result.data?.data || [];
    const workOrders = apiData.map(transformToProductionFormat);

    // 통계 계산
    const stats: DashboardStats = {
      total: workOrders.length,
      waiting: workOrders.filter((o) => o.status === 'waiting').length,
      inProgress: workOrders.filter((o) => o.status === 'inProgress').length,
      completed: workOrders.filter((o) => o.status === 'completed').length,
      urgent: workOrders.filter((o) => o.isUrgent).length,
      delayed: workOrders.filter((o) => o.isDelayed).length,
    };

    // 작업자별 현황 집계
    const workerMap = new Map<string, WorkerStatus>();
    workOrders.forEach((order) => {
      order.assignees.forEach((name) => {
        if (!name || name === '-') return;

        if (!workerMap.has(name)) {
          workerMap.set(name, {
            id: name,
            name,
            inProgress: 0,
            completed: 0,
            assigned: 0,
          });
        }

        const worker = workerMap.get(name)!;
        worker.assigned++;
        if (order.status === 'inProgress') {
          worker.inProgress++;
        } else if (order.status === 'completed') {
          worker.completed++;
        }
      });
    });

    const workerStatus = Array.from(workerMap.values()).slice(0, 10);

    return {
      success: true,
      workOrders,
      workerStatus,
      stats,
    };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[ProductionDashboardActions] getDashboardData error:', error);
    return {
      ...emptyResult,
      error: '서버 오류가 발생했습니다.',
    };
  }
}
