/**
 * 게시판 게시글 Server Actions
 *
 * API Endpoints:
 * - GET /api/v1/boards/{code}/posts - 게시글 목록
 * - GET /api/v1/boards/{code}/posts/{id} - 게시글 상세
 * - GET /api/v1/my-posts - 나의 게시글
 * - POST /api/v1/boards/{code}/posts - 게시글 작성
 * - PUT /api/v1/boards/{code}/posts/{id} - 게시글 수정
 * - DELETE /api/v1/boards/{code}/posts/{id} - 게시글 삭제
 */

'use server';


import { isNextRedirectError } from '@/lib/utils/redirect-error';
import { serverFetch } from '@/lib/api/fetch-wrapper';
import type {
  PostApiData,
  PostPaginationResponse,
  ApiResponse,
  PostFilters,
  Post,
} from './types';

/**
 * API 데이터 → 프론트엔드 타입 변환
 */
function transformApiToPost(apiData: PostApiData, boardName?: string): Post {
  return {
    id: String(apiData.id),
    boardId: String(apiData.board_id),
    boardCode: apiData.board?.board_code || '',
    boardName: boardName || apiData.board?.name || '',
    title: apiData.title,
    content: apiData.content,
    authorId: String(apiData.user_id),
    authorName: apiData.author?.name || '익명',
    authorDepartment: apiData.author?.department?.name,
    authorPosition: apiData.author?.position,
    isPinned: apiData.is_notice,
    isSecret: apiData.is_secret,
    allowComments: true, // API에서 board 설정 참조 필요
    viewCount: apiData.views,
    attachments: (apiData.files || []).map(file => ({
      id: String(file.id),
      fileName: file.original_name,
      fileSize: file.file_size,
      fileUrl: file.file_path,
      mimeType: file.mime_type,
    })),
    customFields: apiData.custom_field_values || [],
    createdAt: apiData.created_at,
    updatedAt: apiData.updated_at,
  };
}

/**
 * 게시글 목록 조회
 */
export async function getPosts(
  boardCode: string,
  filters?: PostFilters
): Promise<{ success: boolean; data?: PostPaginationResponse; posts?: Post[]; error?: string; __authError?: boolean }> {
  try {
    const params = new URLSearchParams();
    if (filters?.search) params.append('search', filters.search);
    if (filters?.is_notice !== undefined) params.append('is_notice', String(filters.is_notice));
    if (filters?.status) params.append('status', filters.status);
    if (filters?.per_page) params.append('per_page', String(filters.per_page));
    if (filters?.page) params.append('page', String(filters.page));

    const queryString = params.toString();
    const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/boards/${boardCode}/posts${queryString ? `?${queryString}` : ''}`;

    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: '게시글 목록 조회에 실패했습니다.' };
    }

    let result: ApiResponse<PostPaginationResponse>;
    try {
      result = await response.json();
    } catch {
      console.error('[BoardActions] JSON parse error');
      return { success: false, error: '서버 응답 형식 오류입니다.' };
    }

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

    // 프론트엔드 타입으로 변환
    const posts = result.data.data.map(post => transformApiToPost(post));

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

/**
 * 나의 게시글 목록 조회
 */
export async function getMyPosts(
  filters?: PostFilters
): Promise<{ success: boolean; data?: PostPaginationResponse; posts?: Post[]; error?: string; __authError?: boolean }> {
  try {
    const params = new URLSearchParams();
    if (filters?.search) params.append('search', filters.search);
    if (filters?.board_code) params.append('board_code', filters.board_code);
    if (filters?.status) params.append('status', filters.status);
    if (filters?.per_page) params.append('per_page', String(filters.per_page));
    if (filters?.page) params.append('page', String(filters.page));

    const queryString = params.toString();
    const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/my-posts${queryString ? `?${queryString}` : ''}`;

    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: '나의 게시글 조회에 실패했습니다.' };
    }

    let result: ApiResponse<PostPaginationResponse>;
    try {
      result = await response.json();
    } catch {
      console.error('[BoardActions] JSON parse error');
      return { success: false, error: '서버 응답 형식 오류입니다.' };
    }

    if (!response.ok || !result.success) {
      return { success: false, error: result.message || '나의 게시글 조회에 실패했습니다.' };
    }

    // 프론트엔드 타입으로 변환
    const posts = result.data.data.map(post => transformApiToPost(post));

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

/**
 * 게시글 상세 조회
 */
export async function getPost(
  boardCode: string,
  postId: number | string
): Promise<{ success: boolean; data?: Post; error?: string; __authError?: boolean }> {
  try {
    const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/boards/${boardCode}/posts/${postId}`;

    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<PostApiData> = await response.json();

    if (!response.ok || !result.success || !result.data) {
      return { success: false, error: result.message || '게시글을 찾을 수 없습니다.' };
    }

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

/**
 * 게시글 등록
 */
export async function createPost(
  boardCode: string,
  data: {
    title: string;
    content: string;
    is_notice?: boolean;
    is_secret?: boolean;
    custom_fields?: Record<string, string>;
  }
): Promise<{ success: boolean; data?: Post; error?: string; __authError?: boolean }> {
  try {
    const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/boards/${boardCode}/posts`;

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

    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, data: transformApiToPost(result.data) };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[BoardActions] createPost error:', error);
    return { success: false, error: '서버 오류가 발생했습니다.' };
  }
}

/**
 * 게시글 수정
 */
export async function updatePost(
  boardCode: string,
  postId: number | string,
  data: {
    title?: string;
    content?: string;
    is_notice?: boolean;
    is_secret?: boolean;
    custom_fields?: Record<string, string>;
  }
): Promise<{ success: boolean; data?: Post; error?: string; __authError?: boolean }> {
  try {
    const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/boards/${boardCode}/posts/${postId}`;

    const { response, error } = await serverFetch(url, {
      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 = await response.json();

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

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

/**
 * 게시글 삭제
 */
export async function deletePost(
  boardCode: string,
  postId: number | string
): Promise<{ success: boolean; error?: string; __authError?: boolean }> {
  try {
    const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/boards/${boardCode}/posts/${postId}`;

    const { response, error } = await serverFetch(url, {
      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('[BoardActions] deletePost error:', error);
    return { success: false, error: '서버 오류가 발생했습니다.' };
  }
}
