/**
 * 고객센터 공통 Server Actions
 * 시스템 게시판 게시글 API 호출
 */

'use server';


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

/**
 * 게시글 목록 조회
 */
export async function getPosts(
  boardCode: SystemBoardCode,
  filters?: PostFilters
): Promise<{ success: boolean; data?: PostPaginationResponse; 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/system-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('[CustomerCenterActions] JSON parse error');
      return { success: false, error: '서버 응답 형식 오류입니다.' };
    }

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

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

/**
 * 게시글 상세 조회
 */
export async function getPost(
  boardCode: SystemBoardCode,
  postId: number | string
): Promise<{ success: boolean; data?: PostApiData; error?: string; __authError?: boolean }> {
  try {
    const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/system-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: result.data };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[CustomerCenterActions] getPost error:', error);
    return { success: false, error: '서버 오류가 발생했습니다.' };
  }
}

/**
 * 게시글 등록 (1:1 문의용)
 */
export async function createPost(
  boardCode: SystemBoardCode,
  data: {
    title: string;
    content: string;
    is_secret?: boolean;
    custom_fields?: Record<string, string>;
  }
): Promise<{ success: boolean; data?: PostApiData; error?: string; __authError?: boolean }> {
  try {
    const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/system-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: result.data };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[CustomerCenterActions] createPost error:', error);
    return { success: false, error: '서버 오류가 발생했습니다.' };
  }
}

/**
 * 게시글 수정
 */
export async function updatePost(
  boardCode: SystemBoardCode,
  postId: number | string,
  data: {
    title?: string;
    content?: string;
    is_secret?: boolean;
    custom_fields?: Record<string, string>;
  }
): Promise<{ success: boolean; data?: PostApiData; error?: string; __authError?: boolean }> {
  try {
    const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/system-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: result.data };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[CustomerCenterActions] updatePost error:', error);
    return { success: false, error: '서버 오류가 발생했습니다.' };
  }
}

/**
 * 게시글 삭제
 */
export async function deletePost(
  boardCode: SystemBoardCode,
  postId: number | string
): Promise<{ success: boolean; error?: string; __authError?: boolean }> {
  try {
    const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/system-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('[CustomerCenterActions] deletePost error:', error);
    return { success: false, error: '서버 오류가 발생했습니다.' };
  }
}

// ===== 댓글 API =====

/**
 * 댓글 목록 조회
 */
export async function getComments(
  boardCode: SystemBoardCode,
  postId: number | string
): Promise<{ success: boolean; data?: CommentsApiResponse; error?: string; __authError?: boolean }> {
  try {
    const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/system-boards/${boardCode}/posts/${postId}/comments`;

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

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

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

/**
 * 댓글 작성
 */
export async function createComment(
  boardCode: SystemBoardCode,
  postId: number | string,
  content: string
): Promise<{ success: boolean; data?: CommentApiData; error?: string; __authError?: boolean }> {
  try {
    const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/system-boards/${boardCode}/posts/${postId}/comments`;

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

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

/**
 * 댓글 수정
 */
export async function updateComment(
  boardCode: SystemBoardCode,
  postId: number | string,
  commentId: number | string,
  content: string
): Promise<{ success: boolean; data?: CommentApiData; error?: string; __authError?: boolean }> {
  try {
    const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/system-boards/${boardCode}/posts/${postId}/comments/${commentId}`;

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

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

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

    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('[CustomerCenterActions] deleteComment error:', error);
    return { success: false, error: '서버 오류가 발생했습니다.' };
  }
}