/**
 * 직원관리 서버 액션
 *
 * 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 { isNextRedirectError } from '@/lib/utils/redirect-error';
import { cookies } from 'next/headers';
import { serverFetch, getServerApiHeaders } from '@/lib/api/fetch-wrapper';
import type { Employee, EmployeeFormData, EmployeeStats } from './types';
import { transformApiToFrontend, transformFrontendToApi, type EmployeeApiData } from './utils';

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

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

interface PaginatedResponse<T> {
  current_page: number;
  data: T[];
  total: number;
  per_page: number;
  last_page: number;
}

// ============================================
// 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 }> {
  try {
    const searchParams = new URLSearchParams();

    if (params?.page) searchParams.set('page', String(params.page));
    if (params?.per_page) searchParams.set('per_page', String(params.per_page));
    if (params?.q) searchParams.set('q', params.q);
    if (params?.status && params.status !== 'all') {
      searchParams.set('status', params.status);
    }
    if (params?.department_id) searchParams.set('department_id', params.department_id);
    if (params?.has_account !== undefined) {
      searchParams.set('has_account', String(params.has_account));
    }
    if (params?.sort_by) searchParams.set('sort_by', params.sort_by);
    if (params?.sort_dir) searchParams.set('sort_dir', params.sort_dir);

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

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

    // 🚨 401 인증 에러 → 클라이언트에서 로그인 페이지로 리다이렉트
    if (error?.__authError) {
      return { data: [], total: 0, lastPage: 1, __authError: true };
    }

    if (!response || !response.ok) {
      console.error('[EmployeeActions] GET list error:', response?.status);
      return { data: [], total: 0, lastPage: 1 };
    }

    const result: ApiResponse<PaginatedResponse<EmployeeApiData>> = await response.json();

    if (!result.success || !result.data?.data) {
      console.warn('[EmployeeActions] No data in response');
      return { data: [], total: 0, lastPage: 1 };
    }

    return {
      data: result.data.data.map(transformApiToFrontend),
      total: result.data.total,
      lastPage: result.data.last_page,
    };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[EmployeeActions] getEmployees error:', error);
    return { data: [], total: 0, lastPage: 1 };
  }
}

/**
 * 직원 상세 조회
 */
export async function getEmployeeById(id: string): Promise<Employee | null | { __authError: true }> {
  try {
    const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/employees/${id}`;
    const { response, error } = await serverFetch(url, { method: 'GET' });

    // 🚨 401 인증 에러
    if (error?.__authError) {
      return { __authError: true };
    }

    if (!response || !response.ok) {
      console.error('[EmployeeActions] GET employee error:', response?.status);
      return null;
    }

    const result: ApiResponse<EmployeeApiData> = await response.json();

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

    return transformApiToFrontend(result.data);
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[EmployeeActions] getEmployeeById error:', error);
    return null;
  }
}

/**
 * 직원 등록
 */
export async function createEmployee(
  data: EmployeeFormData
): Promise<{
  success: boolean;
  data?: Employee;
  error?: string;
  errors?: Record<string, string[]>;
  status?: number;
  __authError?: boolean;
}> {
  try {
    const apiData = transformFrontendToApi(data);
    const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/employees`;

    console.log('[EmployeeActions] POST employee request:', apiData);

    const { response, error } = await serverFetch(url, {
      method: 'POST',
      body: JSON.stringify(apiData),
    });

    // 🚨 401 인증 에러
    if (error?.__authError) {
      return { success: false, __authError: true };
    }

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

    const result = await response.json();
    console.log('[EmployeeActions] POST employee response:', result);

    if (!response.ok || !result.success) {
      return {
        success: false,
        error: result.message || '직원 등록에 실패했습니다.',
        errors: result.error?.details,  // validation errors: error.details 구조
        status: result.error?.code || response.status,
      };
    }

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

/**
 * 직원 수정
 */
export async function updateEmployee(
  id: string,
  data: EmployeeFormData
): Promise<{ success: boolean; data?: Employee; error?: string; __authError?: boolean }> {
  try {
    const apiData = transformFrontendToApi(data);
    const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/employees/${id}`;

    console.log('[EmployeeActions] PATCH employee request:', apiData);

    const { response, error } = await serverFetch(url, {
      method: 'PATCH',
      body: JSON.stringify(apiData),
    });

    // 🚨 401 인증 에러
    if (error?.__authError) {
      return { success: false, __authError: true };
    }

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

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

/**
 * 직원 삭제 (퇴직 처리)
 */
export async function deleteEmployee(id: string): Promise<{ success: boolean; error?: string; __authError?: boolean }> {
  try {
    const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/employees/${id}`;
    const { response, error } = await serverFetch(url, { method: 'DELETE' });

    // 🚨 401 인증 에러
    if (error?.__authError) {
      return { success: false, __authError: true };
    }

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

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

/**
 * 직원 일괄 삭제
 */
export async function deleteEmployees(ids: string[]): Promise<{ success: boolean; error?: string; __authError?: boolean }> {
  try {
    const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/employees/bulk-delete`;
    const { response, error } = await serverFetch(url, {
      method: 'POST',
      body: JSON.stringify({ ids: ids.map(id => parseInt(id, 10)) }),
    });

    // 🚨 401 인증 에러
    if (error?.__authError) {
      return { success: false, __authError: true };
    }

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

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

/**
 * 직원 통계 조회
 */
export async function getEmployeeStats(): Promise<EmployeeStats | null | { __authError: true }> {
  try {
    const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/employees/stats`;
    const { response, error } = await serverFetch(url, { method: 'GET' });

    // 🚨 401 인증 에러
    if (error?.__authError) {
      return { __authError: true };
    }

    if (!response || !response.ok) {
      console.error('[EmployeeActions] GET stats error:', response?.status);
      return null;
    }

    const result = await response.json();

    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,
    };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[EmployeeActions] getEmployeeStats error:', error);
    return null;
  }
}

// ============================================
// 직급/직책 조회 (positions)
// ============================================

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

/**
 * 직급/직책 목록 조회
 * @param type 'rank' (직급) | 'title' (직책) | undefined (전체)
 */
export async function getPositions(type?: 'rank' | 'title'): Promise<PositionItem[]> {
  try {
    const headers = await getServerApiHeaders();
    const searchParams = new URLSearchParams();
    if (type) {
      searchParams.set('type', type);
    }

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

    const response = await fetch(url, {
      method: 'GET',
      headers,
      cache: 'no-store',
    });

    if (!response.ok) {
      console.error('[EmployeeActions] GET positions error:', response.status);
      return [];
    }

    const result: ApiResponse<PositionItem[]> = await response.json();

    if (!result.success || !result.data) {
      return [];
    }

    return result.data;
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[EmployeeActions] getPositions error:', error);
    return [];
  }
}

// ============================================
// 부서 조회 (departments)
// ============================================

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

/**
 * 부서 목록 조회
 */
export async function getDepartments(): Promise<DepartmentItem[]> {
  try {
    const headers = await getServerApiHeaders();

    const response = await fetch(
      `${process.env.NEXT_PUBLIC_API_URL}/api/v1/departments`,
      {
        method: 'GET',
        headers,
        cache: 'no-store',
      }
    );

    if (!response.ok) {
      console.error('[EmployeeActions] GET departments error:', response.status);
      return [];
    }

    const result = await response.json();

    if (!result.success || !result.data) {
      return [];
    }

    // 페이지네이션 응답 또는 배열 직접 반환 모두 처리
    const departments = Array.isArray(result.data) ? result.data : result.data.data || [];
    return departments;
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[EmployeeActions] getDepartments error:', error);
    return [];
  }
}

// ============================================
// 파일 업로드
// ============================================

export async function uploadProfileImage(inputFormData: FormData): Promise<{
  success: boolean;
  data?: { url: string; path: string };
  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(
      `${process.env.NEXT_PUBLIC_API_URL}/api/v1/files/upload`,
      {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
          'X-API-KEY': process.env.API_KEY || '',
        },
        body: inputFormData,
      }
    );

    // 🚨 401 인증 에러
    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 || '파일 업로드에 실패했습니다.' };
    }

    // 업로드된 파일 경로 추출 (API 응답: file_path 필드)
    const uploadedPath = result.data?.file_path || result.data?.path || result.data?.url;

    if (!uploadedPath) {
      return { success: false, error: '업로드된 파일 경로를 가져올 수 없습니다.' };
    }

    // /storage/tenants/ 경로로 변환 (tenant disk 파일 접근 경로)
    const storagePath = uploadedPath.startsWith('/storage/')
      ? uploadedPath
      : `/storage/tenants/${uploadedPath}`;

    return {
      success: true,
      data: {
        url: `${process.env.NEXT_PUBLIC_API_URL}${storagePath}`,
        path: uploadedPath,
      },
    };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[EmployeeActions] uploadProfileImage error:', error);
    return { success: false, error: '서버 오류가 발생했습니다.' };
  }
}