package com.aiosman.ravenow.data

import com.aiosman.ravenow.data.api.ApiClient
import com.aiosman.ravenow.data.api.CommentRequestBody
import com.aiosman.ravenow.entity.CommentEntity
import com.google.gson.annotations.SerializedName

/**
 * 评论相关 Service
 */
interface CommentService {
    /**
     * 获取动态
     * @param pageNumber 页码
     * @param postId 动态ID,过滤条件
     * @param postUser 动态作者ID,获取某个用户所有动态下的评论
     * @param selfNotice 是否是自己的通知
     * @param order 排序
     * @param parentCommentId 父评论ID
     * @param pageSize 每页数量
     * @return 评论列表
     */
    suspend fun getComments(
        pageNumber: Int,
        postId: Int? = null,
        postUser: Int? = null,
        selfNotice: Boolean? = null,
        order: String? = null,
        parentCommentId: Int? = null,
        pageSize: Int? = null
    ): ListContainer<CommentEntity>

    /**
     * 创建评论
     * @param postId 动态ID
     * @param content 评论内容
     * @param parentCommentId 父评论ID
     * @param replyUserId 回复用户ID
     */
    suspend fun createComment(
        postId: Int,
        content: String,
        parentCommentId: Int? = null,
        replyUserId: Int? = null,
        replyCommentId: Int? = null
    ): CommentEntity

    /**
     * 点赞评论
     * @param commentId 评论ID
     */
    suspend fun likeComment(commentId: Int)

    /**
     * 取消点赞评论
     * @param commentId 评论ID
     */
    suspend fun dislikeComment(commentId: Int)

    /**
     * 更新评论已读状态
     * @param commentId 评论ID
     */
    suspend fun updateReadStatus(commentId: Int)

    /**
     * 删除评论
     * @param commentId 评论ID
     */
    suspend fun DeleteComment(commentId: Int)

    /**
     * 获取评论
     * @param commentId 评论ID
     */
    suspend fun getCommentById(commentId: Int): CommentEntity

}

/**
 * 评论
 */
data class Comment(
    // 评论ID
    @SerializedName("id")
    val id: Int,
    // 评论内容
    @SerializedName("content")
    val content: String,
    // 评论用户
    @SerializedName("user")
    val user: User,
    // 点赞数
    @SerializedName("likeCount")
    val likeCount: Int,
    // 是否点赞
    @SerializedName("isLiked")
    val isLiked: Boolean,
    // 创建时间
    @SerializedName("createdAt")
    val createdAt: String,
    // 动态ID
    @SerializedName("postId")
    val postId: Int,
    // 动态
    @SerializedName("post")
    val post: NoticePost?,
    // 是否未读
    @SerializedName("isUnread")
    val isUnread: Boolean,
    @SerializedName("reply")
    val reply: List<Comment>,
    @SerializedName("replyUser")
    val replyUser: User?,
    @SerializedName("parentCommentId")
    val parentCommentId: Int?,
    @SerializedName("replyCount")
    val replyCount: Int
) {
    /**
     * 转换为Entity
     */
    fun toCommentEntity(): CommentEntity {
        return CommentEntity(
            id = id,
            name = user.nickName,
            comment = content,
            date = ApiClient.dateFromApiString(createdAt),
            likes = likeCount,
            postId = postId,
            avatar = "${ApiClient.BASE_SERVER}${user.avatar}",
            author = user.id,
            liked = isLiked,
            unread = isUnread,
            post = post?.let {
                it.copy(
                    images = it.images.map {
                        it.copy(
                            url = "${ApiClient.BASE_SERVER}${it.url}",
                            thumbnail = "${ApiClient.BASE_SERVER}${it.thumbnail}"
                        )
                    }
                )
            },
            reply = reply.map { it.toCommentEntity() },
            replyUserNickname = replyUser?.nickName,
            replyUserId = replyUser?.id,
            replyUserAvatar = replyUser?.avatar?.let { "${ApiClient.BASE_SERVER}$it" },
            parentCommentId = parentCommentId,
            replyCount = replyCount
        )
    }
}

class CommentRemoteDataSource(
    private val commentService: CommentService,
) {
    suspend fun getComments(
        pageNumber: Int,
        postId: Int?,
        postUser: Int?,
        selfNotice: Boolean?,
        order: String?,
        parentCommentId: Int?,
        pageSize: Int? = 20
    ): ListContainer<CommentEntity> {
        return commentService.getComments(
            pageNumber,
            postId,
            postUser = postUser,
            selfNotice = selfNotice,
            order = order,
            parentCommentId = parentCommentId,
            pageSize = pageSize
        )
    }
}


class CommentServiceImpl : CommentService {
    override suspend fun getComments(
        pageNumber: Int,
        postId: Int?,
        postUser: Int?,
        selfNotice: Boolean?,
        order: String?,
        parentCommentId: Int?,
        pageSize: Int?
    ): ListContainer<CommentEntity> {
        val resp = ApiClient.api.getComments(
            page = pageNumber,
            postId = postId,
            postUser = postUser,
            order = order,
            selfNotice = selfNotice?.let {
                if (it) 1 else 0
            },
            parentCommentId = parentCommentId,
            pageSize = pageSize ?: 20
        )
        val body = resp.body() ?: throw ServiceException("Failed to get comments")
        return ListContainer(
            list = body.list.map { it.toCommentEntity() },
            page = body.page,
            total = body.total,
            pageSize = body.pageSize
        )
    }

    override suspend fun createComment(
        postId: Int,
        content: String,
        parentCommentId: Int?,
        replyUserId: Int?,
        replyCommentId: Int?
    ): CommentEntity {
        val resp = ApiClient.api.createComment(
            postId,
            CommentRequestBody(
                content = content,
                parentCommentId = parentCommentId,
                replyUserId = replyUserId,
                replyCommentId = replyCommentId
            ),
        )
        val body = resp.body() ?: throw ServiceException("Failed to create comment")
        return body.data.toCommentEntity()
    }

    override suspend fun likeComment(commentId: Int) {
        val resp = ApiClient.api.likeComment(commentId)
        return
    }

    override suspend fun dislikeComment(commentId: Int) {
        val resp = ApiClient.api.dislikeComment(commentId)
        return
    }

    override suspend fun updateReadStatus(commentId: Int) {
        val resp = ApiClient.api.updateReadStatus(commentId)
        return
    }

    override suspend fun DeleteComment(commentId: Int) {
        val resp = ApiClient.api.deleteComment(commentId)
        return
    }

    override suspend fun getCommentById(commentId: Int): CommentEntity {
        val resp = ApiClient.api.getComment(commentId)
        val body = resp.body() ?: throw ServiceException("Failed to get comment")
        return body.data.toCommentEntity()
    }
}