/**
 * 직원관리 서버 액션
 *
 * API Endpoints:
 * - GET /api/v1/employees - 목록 조회
 * - GET /api/v1/employees/{id} - 상세 조회
 * - POST /api/v1/employees - 등록
 * - PATCH /api/v1/employees/{id} - 수정
 * - DELETE /api/v1/employees/{id} - 삭제
 * - POST /api/v1/employees/bulk-delete - 일괄 삭제
 * - GET /api/v1/employees/stats - 통계
 *
 * 🚨 401 에러 시 __authError: true 반환 → 클라이언트에서 로그인 페이지로 리다이렉트
 */

'use server';


import { executeServerAction } from '@/lib/api/execute-server-action';
import { buildApiUrl } from '@/lib/api/query-params';
import type { PaginatedApiResponse } from '@/lib/api/types';
import { isNextRedirectError } from '@/lib/utils/redirect-error';
import { cookies } from 'next/headers';
import type { Employee, EmployeeFormData, EmployeeStats } from './types';
import { transformApiToFrontend, transformFrontendToApi, type EmployeeApiData } from './utils';

// ============================================
// API 응답 타입 정의
// ============================================

interface _ApiResponse<T> {
  success: boolean;
  data: T;
  message: string;
}

const API_URL = process.env.NEXT_PUBLIC_API_URL;

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

export async function getEmployees(params?: {
  page?: number; per_page?: number; q?: string; status?: string;
  department_id?: string; has_account?: boolean;
  sort_by?: string; sort_dir?: 'asc' | 'desc';
}): Promise<{ data: Employee[]; total: number; lastPage: number; __authError?: boolean }> {
  const result = await executeServerAction<PaginatedApiResponse<EmployeeApiData>>({
    url: buildApiUrl('/api/v1/employees', {
      page: params?.page,
      per_page: params?.per_page,
      q: params?.q,
      status: params?.status && params.status !== 'all' ? params.status : undefined,
      department_id: params?.department_id,
      has_account: params?.has_account,
      sort_by: params?.sort_by,
      sort_dir: params?.sort_dir,
    }),
    errorMessage: '직원 목록 조회에 실패했습니다.',
  });

  if (result.__authError) return { data: [], total: 0, lastPage: 1, __authError: true };
  if (!result.success || !result.data?.data) return { data: [], total: 0, lastPage: 1 };

  return {
    data: result.data.data.map(transformApiToFrontend),
    total: result.data.total,
    lastPage: result.data.last_page,
  };
}

export async function getEmployeeById(id: string): Promise<Employee | null | { __authError: true }> {
  const result = await executeServerAction({
    url: buildApiUrl(`/api/v1/employees/${id}`),
    transform: (data: EmployeeApiData) => transformApiToFrontend(data),
    errorMessage: '직원 조회에 실패했습니다.',
  });

  if (result.__authError) return { __authError: true };
  return result.success ? result.data || null : null;
}

export async function createEmployee(
  data: EmployeeFormData
): Promise<{
  success: boolean; data?: Employee; error?: string;
  errors?: Record<string, string[]>; status?: number; __authError?: boolean;
}> {
  const apiData = transformFrontendToApi(data);
  const result = await executeServerAction({
    url: buildApiUrl('/api/v1/employees'),
    method: 'POST',
    body: apiData,
    transform: (d: EmployeeApiData) => transformApiToFrontend(d),
    errorMessage: '직원 등록에 실패했습니다.',
  });

  if (result.__authError) return { success: false, __authError: true };
  return { success: result.success, data: result.data, error: result.error };
}

export async function updateEmployee(
  id: string,
  data: EmployeeFormData
): Promise<{ success: boolean; data?: Employee; error?: string; __authError?: boolean }> {
  const apiData = transformFrontendToApi(data);
  const result = await executeServerAction({
    url: buildApiUrl(`/api/v1/employees/${id}`),
    method: 'PATCH',
    body: apiData,
    transform: (d: EmployeeApiData) => transformApiToFrontend(d),
    errorMessage: '직원 수정에 실패했습니다.',
  });

  if (result.__authError) return { success: false, __authError: true };
  return { success: result.success, data: result.data, error: result.error };
}

export async function deleteEmployee(id: string): Promise<{ success: boolean; error?: string; __authError?: boolean }> {
  const result = await executeServerAction({
    url: buildApiUrl(`/api/v1/employees/${id}`),
    method: 'DELETE',
    errorMessage: '직원 삭제에 실패했습니다.',
  });

  if (result.__authError) return { success: false, __authError: true };
  return { success: result.success, error: result.error };
}

export async function deleteEmployees(ids: string[]): Promise<{ success: boolean; error?: string; __authError?: boolean }> {
  const result = await executeServerAction({
    url: buildApiUrl('/api/v1/employees/bulk-delete'),
    method: 'POST',
    body: { ids: ids.map(id => parseInt(id, 10)) },
    errorMessage: '직원 일괄 삭제에 실패했습니다.',
  });

  if (result.__authError) return { success: false, __authError: true };
  return { success: result.success, error: result.error };
}

interface EmployeeStatsApiData {
  active_count: number;
  leave_count: number;
  resigned_count: number;
  average_tenure: number;
}

export async function getEmployeeStats(): Promise<EmployeeStats | null | { __authError: true }> {
  const result = await executeServerAction<EmployeeStatsApiData>({
    url: buildApiUrl('/api/v1/employees/stats'),
    errorMessage: '직원 통계 조회에 실패했습니다.',
  });

  if (result.__authError) return { __authError: true };
  if (!result.success || !result.data) return null;

  return {
    activeCount: result.data.active_count ?? 0,
    leaveCount: result.data.leave_count ?? 0,
    resignedCount: result.data.resigned_count ?? 0,
    averageTenure: result.data.average_tenure ?? 0,
  };
}

// ============================================
// 직급/직책 조회 (native fetch - keep as-is)
// ============================================

export interface PositionItem {
  id: number;
  key: string;
  name: string;
  type: 'rank' | 'title';
  sort_order: number;
  is_active: boolean;
}

export async function getPositions(type?: 'rank' | 'title'): Promise<PositionItem[]> {
  const result = await executeServerAction<PositionItem[]>({
    url: buildApiUrl('/api/v1/positions', {
      type,
    }),
    errorMessage: '직급/직책 조회에 실패했습니다.',
  });
  return result.data || [];
}

// ============================================
// 부서 조회 (native fetch - keep as-is)
// ============================================

export interface DepartmentItem {
  id: number;
  name: string;
  code: string | null;
  parent_id: number | null;
  is_active: boolean;
}

export async function getDepartments(): Promise<DepartmentItem[]> {
  const result = await executeServerAction<DepartmentItem[] | { data: DepartmentItem[] }>({
    url: buildApiUrl('/api/v1/departments'),
    errorMessage: '부서 조회에 실패했습니다.',
  });
  if (!result.data) return [];
  return Array.isArray(result.data) ? result.data : result.data.data || [];
}

// ============================================
// 파일 업로드 (native fetch - keep as-is)
// ============================================

export async function uploadProfileImage(inputFormData: FormData): Promise<{
  success: boolean;
  data?: { url: string; path: string; fileId?: number };
  error?: string;
  __authError?: boolean;
}> {
  try {
    const cookieStore = await cookies();
    const token = cookieStore.get('access_token')?.value;

    if (!token) return { success: false, __authError: true };

    inputFormData.append('directory', 'employees/profiles');

    const response = await fetch(
      `${API_URL}/api/v1/files/upload`,
      {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
          'X-API-KEY': process.env.API_KEY || '',
        },
        body: inputFormData,
      }
    );

    if (response.status === 401) return { success: false, __authError: true };
    if (!response.ok) return { success: false, error: `파일 업로드 실패: ${response.status}` };

    const result = await response.json();
    if (!result.success) return { success: false, error: result.message || '파일 업로드에 실패했습니다.' };

    // R2 전환: /storage/ 직접 접근 불가 → /api/proxy/files/{id}/view 사용
    const fileId = result.data?.id;
    const uploadedPath = result.data?.file_path || result.data?.path || '';

    // file_id가 있으면 프록시 경로 사용, 없으면 fallback
    const viewUrl = fileId
      ? `/api/proxy/files/${fileId}/view`
      : uploadedPath;

    return {
      success: true,
      data: {
        url: viewUrl,
        path: uploadedPath,
        fileId,
      },
    };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    return { success: false, error: '서버 오류가 발생했습니다.' };
  }
}
