'use server';


import { isNextRedirectError } from '@/lib/utils/redirect-error';
import { serverFetch } from '@/lib/api/fetch-wrapper';
import type { Title } from './types';

// ===== API 응답 타입 =====
interface PositionApiData {
  id: number;
  tenant_id: number;
  type: 'rank' | 'title';
  name: string;
  sort_order: number;
  is_active: boolean;
  created_at?: string;
  updated_at?: string;
}

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

// ===== 데이터 변환: API → Frontend =====
function transformApiToFrontend(apiData: PositionApiData): Title {
  return {
    id: apiData.id,
    name: apiData.name,
    order: apiData.sort_order,
    isActive: apiData.is_active,
    createdAt: apiData.created_at,
    updatedAt: apiData.updated_at,
  };
}

// ===== 직책 목록 조회 =====
export async function getTitles(params?: {
  is_active?: boolean;
  q?: string;
}): Promise<{
  success: boolean;
  data?: Title[];
  error?: string;
  __authError?: boolean;
}> {
  try {
    const searchParams = new URLSearchParams();
    searchParams.set('type', 'title');

    if (params?.is_active !== undefined) {
      searchParams.set('is_active', params.is_active.toString());
    }
    if (params?.q) {
      searchParams.set('q', params.q);
    }

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

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

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

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

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

    if (!response.ok || !result.success) {
      return { success: false, error: result.message || '직책 목록 조회에 실패했습니다.' };
    }

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

// ===== 직책 생성 =====
export async function createTitle(data: {
  name: string;
  sort_order?: number;
  is_active?: boolean;
}): Promise<{
  success: boolean;
  data?: Title;
  error?: string;
  __authError?: boolean;
}> {
  try {
    const { response, error } = await serverFetch(
      `${process.env.NEXT_PUBLIC_API_URL}/api/v1/positions`,
      {
        method: 'POST',
        body: JSON.stringify({
          type: 'title',
          name: data.name,
          sort_order: data.sort_order,
          is_active: data.is_active ?? true,
        }),
      }
    );

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

    if (!response) {
      return { success: false, error: '직책 생성에 실패했습니다.' };
    }

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

    if (!response.ok || !result.success) {
      return { success: false, error: result.message || '직책 생성에 실패했습니다.' };
    }

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

// ===== 직책 수정 =====
export async function updateTitle(
  id: number,
  data: {
    name?: string;
    sort_order?: number;
    is_active?: boolean;
  }
): Promise<{
  success: boolean;
  data?: Title;
  error?: string;
  __authError?: boolean;
}> {
  try {
    const { response, error } = await serverFetch(
      `${process.env.NEXT_PUBLIC_API_URL}/api/v1/positions/${id}`,
      {
        method: 'PUT',
        body: JSON.stringify(data),
      }
    );

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

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

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

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

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

// ===== 직책 삭제 =====
export async function deleteTitle(id: number): Promise<{
  success: boolean;
  error?: string;
  __authError?: boolean;
}> {
  try {
    const { response, error } = await serverFetch(
      `${process.env.NEXT_PUBLIC_API_URL}/api/v1/positions/${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();

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

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

// ===== 직책 순서 변경 =====
export async function reorderTitles(
  items: { id: number; sort_order: number }[]
): Promise<{
  success: boolean;
  error?: string;
  __authError?: boolean;
}> {
  try {
    const { response, error } = await serverFetch(
      `${process.env.NEXT_PUBLIC_API_URL}/api/v1/positions/reorder`,
      {
        method: 'PUT',
        body: JSON.stringify({ items }),
      }
    );

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

    if (!response) {
      return { success: false, error: '순서 변경에 실패했습니다.' };
    }

    const result = await response.json();

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

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