/**
 * 팝업관리 서버 액션
 *
 * 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 { executeServerAction, type ActionResult } from '@/lib/api/execute-server-action';
import { buildApiUrl } from '@/lib/api/query-params';
import type { PaginatedApiResponse } from '@/lib/api/types';
import type { Popup, PopupFormData } from './types';
import { transformApiToFrontend, transformFrontendToApi, type PopupApiData } from './utils';

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

/**
 * 팝업 목록 조회
 */
export async function getPopups(params?: {
  page?: number;
  size?: number;
  status?: string;
}): Promise<Popup[]> {
  const result = await executeServerAction({
    url: buildApiUrl('/api/v1/popups', {
      page: params?.page,
      size: params?.size,
      status: params?.status !== 'all' ? params?.status : undefined,
    }),
    transform: (data: PaginatedApiResponse<PopupApiData>) => data.data.map(transformApiToFrontend),
    errorMessage: '팝업 목록 조회에 실패했습니다.',
  });
  return result.data || [];
}

/**
 * 팝업 상세 조회
 */
export async function getPopupById(id: string): Promise<Popup | null> {
  const result = await executeServerAction({
    url: buildApiUrl(`/api/v1/popups/${id}`),
    transform: (data: PopupApiData) => transformApiToFrontend(data),
    errorMessage: '팝업 조회에 실패했습니다.',
  });
  return result.data || null;
}

/**
 * 팝업 등록
 */
export async function createPopup(
  data: PopupFormData
): Promise<ActionResult<Popup>> {
  return executeServerAction({
    url: buildApiUrl('/api/v1/popups'),
    method: 'POST',
    body: transformFrontendToApi(data),
    transform: (data: PopupApiData) => transformApiToFrontend(data),
    errorMessage: '팝업 등록에 실패했습니다.',
  });
}

/**
 * 팝업 수정
 */
export async function updatePopup(
  id: string,
  data: PopupFormData
): Promise<ActionResult<Popup>> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/popups/${id}`),
    method: 'PUT',
    body: transformFrontendToApi(data),
    transform: (data: PopupApiData) => transformApiToFrontend(data),
    errorMessage: '팝업 수정에 실패했습니다.',
  });
}

/**
 * 팝업 삭제
 */
export async function deletePopup(id: string): Promise<ActionResult> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/popups/${id}`),
    method: 'DELETE',
    errorMessage: '팝업 삭제에 실패했습니다.',
  });
}

/**
 * 부서 목록 조회 (팝업 대상 선택용)
 */
export async function getDepartmentList(): Promise<{ id: number; name: string }[]> {
  const result = await executeServerAction({
    url: buildApiUrl('/api/v1/departments'),
    transform: (data: { data: { id: number; name: string }[] }) =>
      data.data.map((d) => ({ id: d.id, name: d.name })),
    errorMessage: '부서 목록 조회에 실패했습니다.',
  });
  return result.data || [];
}

/**
 * 팝업 일괄 삭제
 */
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: '서버 오류가 발생했습니다.' };
  }
}
