'use server';


import { executeServerAction, type ActionResult } from '@/lib/api/execute-server-action';
import { buildApiUrl } from '@/lib/api/query-params';
import type {
  PostApiData,
  PostPaginationResponse,
  PostFilters,
  Post,
} from './types';

// ===== 변환 =====
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,
    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 }> {
  const result = await executeServerAction({
    url: buildApiUrl(`/api/v1/boards/${boardCode}/posts`, {
      search: filters?.search,
      is_notice: filters?.is_notice,
      status: filters?.status,
      per_page: filters?.per_page,
      page: filters?.page,
      board_code: filters?.board_code,
    }),
    transform: (data: PostPaginationResponse) => ({
      raw: data,
      posts: data.data.map(post => transformApiToPost(post)),
    }),
    errorMessage: '게시글 목록 조회에 실패했습니다.',
  });
  return { success: result.success, data: result.data?.raw, posts: result.data?.posts, error: result.error, __authError: result.__authError };
}

// ===== 나의 게시글 목록 조회 =====
export async function getMyPosts(
  filters?: PostFilters
): Promise<{ success: boolean; data?: PostPaginationResponse; posts?: Post[]; error?: string; __authError?: boolean }> {
  const result = await executeServerAction({
    url: buildApiUrl('/api/v1/my-posts', {
      search: filters?.search,
      is_notice: filters?.is_notice,
      status: filters?.status,
      per_page: filters?.per_page,
      page: filters?.page,
      board_code: filters?.board_code,
    }),
    transform: (data: PostPaginationResponse) => ({
      raw: data,
      posts: data.data.map(post => transformApiToPost(post)),
    }),
    errorMessage: '나의 게시글 조회에 실패했습니다.',
  });
  return { success: result.success, data: result.data?.raw, posts: result.data?.posts, error: result.error, __authError: result.__authError };
}

// ===== 게시글 상세 조회 =====
export async function getPost(boardCode: string, postId: number | string): Promise<ActionResult<Post>> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/boards/${boardCode}/posts/${postId}`),
    transform: (data: PostApiData) => transformApiToPost(data),
    errorMessage: '게시글을 찾을 수 없습니다.',
  });
}

// ===== 게시글 등록 =====
export async function createPost(
  boardCode: string,
  data: { title: string; content: string; is_notice?: boolean; is_secret?: boolean; custom_fields?: Record<string, string> }
): Promise<ActionResult<Post>> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/boards/${boardCode}/posts`),
    method: 'POST',
    body: data,
    transform: (d: PostApiData) => transformApiToPost(d),
    errorMessage: '게시글 등록에 실패했습니다.',
  });
}

// ===== 게시글 수정 =====
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<ActionResult<Post>> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/boards/${boardCode}/posts/${postId}`),
    method: 'PUT',
    body: data,
    transform: (d: PostApiData) => transformApiToPost(d),
    errorMessage: '게시글 수정에 실패했습니다.',
  });
}

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