'use server';


import { executeServerAction, type ActionResult } from '@/lib/api/execute-server-action';
import { buildApiUrl } from '@/lib/api/query-params';
import { isNextRedirectError } from '@/lib/utils/redirect-error';
import type { Board, BoardApiData, BoardFormData } from './types';

// ===== 변환 =====
function transformApiToFrontend(apiData: BoardApiData): Board {
  const extraSettings = apiData.extra_settings || {};
  const permissions = extraSettings.permissions?.read || [];
  return {
    id: String(apiData.id),
    boardCode: apiData.board_code,
    boardType: apiData.board_type || undefined,
    target: extraSettings.target || 'all',
    targetId: extraSettings.target_id,
    targetName: extraSettings.target_name,
    permissions: permissions.length > 0 ? permissions : undefined,
    boardName: apiData.name,
    description: apiData.description || undefined,
    status: apiData.is_active ? 'active' : 'inactive',
    isSystem: apiData.is_system,
    authorId: apiData.created_by ? String(apiData.created_by) : '',
    authorName: apiData.creator?.name || '시스템',
    createdAt: apiData.created_at,
    updatedAt: apiData.updated_at,
  };
}

function transformFrontendToApi(data: BoardFormData & { boardCode?: string; description?: string }, isUpdate = false): Record<string, unknown> {
  const extraSettings: Record<string, unknown> = {
    target: data.target,
    target_name: data.target === 'department' ? data.targetName : null,
  };
  if (data.target === 'permission' && data.permissions && data.permissions.length > 0) {
    extraSettings.permissions = { read: data.permissions, write: data.permissions, manage: data.permissions };
  }
  const result: Record<string, unknown> = {
    name: data.boardName, description: data.description || null,
    is_active: data.status === 'active', extra_settings: extraSettings,
  };
  if (!isUpdate && data.boardCode) result.board_code = data.boardCode;
  return result;
}

// ===== 게시판 목록 조회 =====
export async function getBoards(filters?: {
  board_type?: string; search?: string;
}): Promise<ActionResult<Board[]>> {
  return executeServerAction({
    url: buildApiUrl('/api/v1/boards/tenant', {
      board_type: filters?.board_type,
      search: filters?.search,
    }),
    transform: (data: BoardApiData[]) => (Array.isArray(data) ? data : []).map(transformApiToFrontend),
    errorMessage: '게시판 목록 조회에 실패했습니다.',
  });
}

// ===== 테넌트 게시판만 조회 =====
export async function getTenantBoards(filters?: {
  board_type?: string; search?: string;
}): Promise<ActionResult<Board[]>> {
  return executeServerAction({
    url: buildApiUrl('/api/v1/boards/tenant', {
      board_type: filters?.board_type,
      search: filters?.search,
    }),
    transform: (data: BoardApiData[]) => data.map(transformApiToFrontend),
    errorMessage: '테넌트 게시판 목록 조회에 실패했습니다.',
  });
}

// ===== 게시판 상세 조회 (코드 기반) =====
export async function getBoardByCode(code: string): Promise<ActionResult<Board>> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/boards/${code}`),
    transform: (data: BoardApiData) => transformApiToFrontend(data),
    errorMessage: '게시판을 찾을 수 없습니다.',
  });
}

// ===== 게시판 상세 조회 (ID 기반) =====
export async function getBoardById(id: string): Promise<ActionResult<Board>> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/boards/${id}`),
    transform: (data: BoardApiData) => transformApiToFrontend(data),
    errorMessage: '게시판을 찾을 수 없습니다.',
  });
}

// ===== 게시판 생성 =====
export async function createBoard(
  data: BoardFormData & { boardCode: string; description?: string }
): Promise<ActionResult<Board>> {
  return executeServerAction({
    url: buildApiUrl('/api/v1/boards'),
    method: 'POST',
    body: transformFrontendToApi(data),
    transform: (d: BoardApiData) => transformApiToFrontend(d),
    errorMessage: '게시판 생성에 실패했습니다.',
  });
}

// ===== 게시판 수정 =====
export async function updateBoard(
  id: string,
  data: BoardFormData & { boardCode?: string; description?: string }
): Promise<ActionResult<Board>> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/boards/${id}`),
    method: 'PUT',
    body: transformFrontendToApi(data, true),
    transform: (d: BoardApiData) => transformApiToFrontend(d),
    errorMessage: '게시판 수정에 실패했습니다.',
  });
}

// ===== 게시판 삭제 =====
export async function deleteBoard(id: string): Promise<ActionResult> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/boards/${id}`),
    method: 'DELETE',
    errorMessage: '게시판 삭제에 실패했습니다.',
  });
}

// ===== 게시판 일괄 삭제 =====
export async function deleteBoardsBulk(ids: string[]): Promise<ActionResult> {
  try {
    const results = await Promise.all(ids.map(id => deleteBoard(id)));
    const failed = results.filter(r => !r.success);
    const hasAuthError = results.some(r => r.__authError);
    if (hasAuthError) return { success: false, error: '인증이 만료되었습니다.', __authError: true };
    if (failed.length > 0) return { success: false, error: `${failed.length}개의 게시판 삭제에 실패했습니다.` };
    return { success: true };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    return { success: false, error: '서버 오류가 발생했습니다.' };
  }
}
