/**
 * 评论服务
 * 处理评论的增删改查、点赞等功能
 */

import { api, PaginatedData } from './api';
import { Comment, CreateCommentInput } from '../types';
import { CursorPaginationRequest, CursorPaginationResponse, CommentDTO } from '../types/dto';

// 评论列表响应
interface CommentListResponse {
  list: Comment[];
  total: number;
  page: number;
  page_size: number;
  total_pages: number;
}

// 评论响应
type CommentResponse = Comment;

// 创建评论请求
interface CreateCommentRequest {
  postId: string;
  content: string;
  parentId?: string;
  images?: string[]; // 图片URL列表
  replyToUserId?: string;
}

// 更新评论请求
interface UpdateCommentRequest {
  content: string;
}

// 评论服务类
class CommentService {
  // 获取帖子的评论列表
  async getPostComments(
    postId: string,
    page = 1,
    pageSize = 20,
    sort: 'latest' | 'hot' = 'latest'
  ): Promise<PaginatedData<Comment>> {
    try {
      const response = await api.get<CommentListResponse>(`/comments/post/${postId}`, {
        page,
        page_size: pageSize,
        sort,
      });
      return response.data;
    } catch (error) {
      console.error('获取评论列表失败:', error);
      return {
        list: [],
        total: 0,
        page: 1,
        page_size: pageSize,
        total_pages: 0,
      };
    }
  }

  // 获取评论的回复列表
  async getCommentReplies(
    commentId: string,
    page = 1,
    pageSize = 20
  ): Promise<PaginatedData<Comment>> {
    try {
      const response = await api.get<CommentListResponse>(`/comments/${commentId}/replies`, {
        page,
        page_size: pageSize,
      });
      return response.data;
    } catch (error) {
      console.error('获取评论回复列表失败:', error);
      return {
        list: [],
        total: 0,
        page: 1,
        page_size: pageSize,
        total_pages: 0,
      };
    }
  }

  // 根据根评论ID分页获取回复（扁平化）
  async getFlatReplies(
    rootId: string,
    page = 1,
    pageSize = 10
  ): Promise<PaginatedData<Comment>> {
    try {
      const response = await api.get<CommentListResponse>(`/comments/${rootId}/replies/flat`, {
        page,
        page_size: pageSize,
      });
      return response.data;
    } catch (error) {
      console.error('获取扁平化回复列表失败:', error);
      return {
        list: [],
        total: 0,
        page: 1,
        page_size: pageSize,
        total_pages: 0,
      };
    }
  }

  // 获取评论详情
  async getComment(commentId: string): Promise<Comment | null> {
    try {
      const response = await api.get<CommentResponse>(`/comments/${commentId}`);
      return response.data;
    } catch (error) {
      console.error('获取评论详情失败:', error);
      return null;
    }
  }

  // 创建评论
  async createComment(data: CreateCommentRequest): Promise<Comment | null> {
    try {
      // 转换字段名为后端期望的snake_case
      // 只有当 parentId 有值时才包含 parent_id 字段
      const requestBody: Record<string, any> = {
        post_id: data.postId,
        content: data.content,
      };
      
      // 如果有父评论ID，才添加 parent_id 字段
      if (data.parentId) {
        requestBody.parent_id = data.parentId;
      }
      
      // 如果有图片，添加 images 字段
      if (data.images && data.images.length > 0) {
        requestBody.images = data.images;
      }
      
      const response = await api.post<CommentResponse>('/comments', requestBody);
      return response.data;
    } catch (error) {
      console.error('创建评论失败:', error);
      return null;
    }
  }

  // 回复评论
  async replyComment(
    postId: string,
    parentId: string,
    content: string,
    replyToUserId?: string
  ): Promise<Comment | null> {
    return this.createComment({
      postId,
      content,
      parentId,
      replyToUserId,
    });
  }

  // 更新评论
  async updateComment(commentId: string, content: string): Promise<Comment | null> {
    try {
      const response = await api.put<CommentResponse>(`/comments/${commentId}`, { content });
      return response.data;
    } catch (error) {
      console.error('更新评论失败:', error);
      return null;
    }
  }

  // 删除评论
  async deleteComment(commentId: string): Promise<boolean> {
    try {
      const response = await api.delete(`/comments/${commentId}`);
      return response.code === 0;
    } catch (error) {
      console.error('删除评论失败:', error);
      return false;
    }
  }

  // 点赞评论
  async likeComment(commentId: string): Promise<boolean> {
    try {
      const response = await api.post(`/comments/${commentId}/like`);
      return response.code === 0;
    } catch (error) {
      console.error('点赞评论失败:', error);
      return false;
    }
  }

  // 取消点赞评论
  async unlikeComment(commentId: string): Promise<boolean> {
    try {
      const response = await api.delete(`/comments/${commentId}/like`);
      return response.code === 0;
    } catch (error) {
      console.error('取消点赞评论失败:', error);
      return false;
    }
  }

  // 获取用户评论列表
  async getUserComments(
    userId: string,
    page = 1,
    pageSize = 20
  ): Promise<PaginatedData<Comment>> {
    try {
      const response = await api.get<CommentListResponse>(`/users/${userId}/comments`, {
        page,
        page_size: pageSize,
      });
      return response.data;
    } catch (error) {
      console.error('获取用户评论列表失败:', error);
      return {
        list: [],
        total: 0,
        page: 1,
        page_size: pageSize,
        total_pages: 0,
      };
    }
  }

  // 举报评论
  async reportComment(commentId: string, reason: string): Promise<boolean> {
    try {
      const response = await api.post(`/comments/${commentId}/report`, { reason });
      return response.code === 0;
    } catch (error) {
      console.error('举报评论失败:', error);
      return false;
    }
  }

  // ==================== 游标分页方法 ====================

  /**
   * 获取帖子评论列表（游标分页）
   * GET /api/v1/comments/post/:id/cursor
   * @param postId 帖子ID
   * @param params 游标分页请求参数
   */
  async getPostCommentsCursor(
    postId: string,
    params: CursorPaginationRequest = {}
  ): Promise<CursorPaginationResponse<Comment>> {
    try {
      const response = await api.get<any>(`/comments/post/${postId}/cursor`, params);
      const raw = response.data;
      return {
        list: Array.isArray(raw?.list) ? raw.list : [],
        next_cursor: raw?.next_cursor ?? null,
        prev_cursor: raw?.prev_cursor ?? null,
        has_more: raw?.has_more ?? false,
      };
    } catch (error) {
      console.error('获取帖子评论列表失败:', error);
      return {
        list: [],
        next_cursor: null,
        prev_cursor: null,
        has_more: false,
      };
    }
  }

  /**
   * 获取评论回复列表（游标分页）
   * GET /api/v1/comments/:id/replies/cursor
   * @param commentId 评论ID
   * @param params 游标分页请求参数
   */
  async getCommentRepliesCursor(
    commentId: string,
    params: CursorPaginationRequest = {}
  ): Promise<CursorPaginationResponse<Comment>> {
    try {
      const response = await api.get<any>(`/comments/${commentId}/replies/cursor`, params);
      const raw = response.data;
      return {
        list: Array.isArray(raw?.list) ? raw.list : [],
        next_cursor: raw?.next_cursor ?? null,
        prev_cursor: raw?.prev_cursor ?? null,
        has_more: raw?.has_more ?? false,
      };
    } catch (error) {
      console.error('获取评论回复列表失败:', error);
      return {
        list: [],
        next_cursor: null,
        prev_cursor: null,
        has_more: false,
      };
    }
  }
}

// 导出评论服务实例
export const commentService = new CommentService();
