/**
 * 팝업관리 서버 액션
 *
 * API Endpoints:
 * - GET /api/v1/popups - 목록 조회
 * - GET /api/v1/popups/{id} - 상세 조회
 * - POST /api/v1/popups - 등록
 * - PUT /api/v1/popups/{id} - 수정
 * - DELETE /api/v1/popups/{id} - 삭제
 */

'use server';


import { isNextRedirectError } from '@/lib/utils/redirect-error';
import { serverFetch } from '@/lib/api/fetch-wrapper';
import type { Popup, PopupFormData } from './types';
import { transformApiToFrontend, transformFrontendToApi, type PopupApiData } from './utils';

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

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

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

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

/**
 * 팝업 목록 조회
 */
export async function getPopups(params?: {
  page?: number;
  size?: number;
  status?: string;
}): Promise<Popup[]> {
  try {
    const searchParams = new URLSearchParams();

    if (params?.page) searchParams.set('page', String(params.page));
    if (params?.size) searchParams.set('size', String(params.size));
    if (params?.status && params.status !== 'all') {
      searchParams.set('status', params.status);
    }

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

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

    if (error || !response) {
      console.error('[PopupActions] GET list error:', error?.message);
      return [];
    }

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

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

    if (!result.success || !result.data?.data) {
      console.warn('[PopupActions] No data in response');
      return [];
    }

    return result.data.data.map(transformApiToFrontend);
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[PopupActions] getPopups error:', error);
    return [];
  }
}

/**
 * 팝업 상세 조회
 */
export async function getPopupById(id: string): Promise<Popup | null> {
  try {
    const { response, error } = await serverFetch(
      `${process.env.NEXT_PUBLIC_API_URL}/api/v1/popups/${id}`,
      {
        method: 'GET',
        cache: 'no-store',
      }
    );

    if (error || !response) {
      console.error('[PopupActions] GET popup error:', error?.message);
      return null;
    }

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

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

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

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

/**
 * 팝업 등록
 */
export async function createPopup(
  data: PopupFormData
): Promise<{ success: boolean; data?: Popup; error?: string; __authError?: boolean }> {
  try {
    const apiData = transformFrontendToApi(data);

    console.log('[PopupActions] POST popup request:', apiData);

    const { response, error } = await serverFetch(
      `${process.env.NEXT_PUBLIC_API_URL}/api/v1/popups`,
      {
        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('[PopupActions] POST popup 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('[PopupActions] createPopup error:', error);
    return {
      success: false,
      error: '서버 오류가 발생했습니다.',
    };
  }
}

/**
 * 팝업 수정
 */
export async function updatePopup(
  id: string,
  data: PopupFormData
): Promise<{ success: boolean; data?: Popup; error?: string; __authError?: boolean }> {
  try {
    const apiData = transformFrontendToApi(data);

    console.log('[PopupActions] PUT popup request:', apiData);

    const { response, error } = await serverFetch(
      `${process.env.NEXT_PUBLIC_API_URL}/api/v1/popups/${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('[PopupActions] PUT popup 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('[PopupActions] updatePopup error:', error);
    return {
      success: false,
      error: '서버 오류가 발생했습니다.',
    };
  }
}

/**
 * 팝업 삭제
 */
export async function deletePopup(id: string): Promise<{ success: boolean; error?: string; __authError?: boolean }> {
  try {
    const { response, error } = await serverFetch(
      `${process.env.NEXT_PUBLIC_API_URL}/api/v1/popups/${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('[PopupActions] DELETE popup 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('[PopupActions] deletePopup error:', error);
    return {
      success: false,
      error: '서버 오류가 발생했습니다.',
    };
  }
}

/**
 * 팝업 일괄 삭제
 */
export async function deletePopups(ids: string[]): Promise<{ success: boolean; error?: string }> {
  try {
    const results = await Promise.all(ids.map(id => deletePopup(id)));
    const failed = results.filter(r => !r.success);

    if (failed.length > 0) {
      return {
        success: false,
        error: `${failed.length}개 팝업 삭제에 실패했습니다.`,
      };
    }

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