package cn.meowrain.aioj.backend.blogservice.service.impl;

import cn.meowrain.aioj.backend.blogservice.dao.entity.Collection;
import cn.meowrain.aioj.backend.blogservice.dao.entity.CollectionFolder;
import cn.meowrain.aioj.backend.blogservice.dao.mapper.CollectionFolderMapper;
import cn.meowrain.aioj.backend.blogservice.dao.mapper.CollectionMapper;
import cn.meowrain.aioj.backend.blogservice.dto.req.CollectionFolderCreateRequestDTO;
import cn.meowrain.aioj.backend.blogservice.dto.req.CollectionRequestDTO;
import cn.meowrain.aioj.backend.blogservice.dto.resp.ArticleListResponseDTO;
import cn.meowrain.aioj.backend.blogservice.dto.resp.CollectionFolderResponseDTO;
import cn.meowrain.aioj.backend.blogservice.service.CollectionService;
import cn.meowrain.aioj.backend.framework.core.exception.ClientException;
import cn.meowrain.aioj.backend.framework.core.utils.ContextHolderUtils;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 收藏服务实现类
 *
 * @author AIOJ
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class CollectionServiceImpl extends ServiceImpl<CollectionMapper, Collection> implements CollectionService {

    private final CollectionFolderMapper collectionFolderMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean collectArticle(CollectionRequestDTO request) {
        Long currentUserId = ContextHolderUtils.getCurrentUserId();

        // 检查是否已收藏
        Collection existingCollection = this.lambdaQuery()
                .eq(Collection::getUserId, currentUserId)
                .eq(Collection::getArticleId, request.getArticleId())
                .eq(Collection::getIsCancelled, 0)
                .one();

        if (existingCollection != null) {
            throw new ClientException("已经收藏过了");
        }

        // 创建收藏记录
        Collection collection = new Collection()
                .setUserId(currentUserId)
                .setArticleId(request.getArticleId())
                .setFolderId(request.getFolderId() != null ? request.getFolderId() : 0L)
                .setNote(request.getNote())
                .setIsCancelled(0);
        this.save(collection);

        // TODO: 更新文章收藏数、收藏夹收藏数

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean uncollectArticle(Long articleId) {
        Long currentUserId = ContextHolderUtils.getCurrentUserId();

        Collection collection = this.lambdaQuery()
                .eq(Collection::getUserId, currentUserId)
                .eq(Collection::getArticleId, articleId)
                .eq(Collection::getIsCancelled, 0)
                .one();

        if (collection == null) {
            throw new ClientException("未收藏过该文章");
        }

        collection.setIsCancelled(1);
        collection.setUpdateTime(new Date());
        this.updateById(collection);

        // TODO: 更新文章收藏数、收藏夹收藏数

        return true;
    }

    @Override
    public Boolean isCollected(Long userId, Long articleId) {
        Collection collection = this.lambdaQuery()
                .eq(Collection::getUserId, userId)
                .eq(Collection::getArticleId, articleId)
                .eq(Collection::getIsCancelled, 0)
                .one();
        return collection != null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createCollectionFolder(CollectionFolderCreateRequestDTO request) {
        Long currentUserId = ContextHolderUtils.getCurrentUserId();

        CollectionFolder folder = new CollectionFolder()
                .setUserId(currentUserId)
                .setName(request.getName())
                .setDescription(request.getDescription())
                .setIsPublic(request.getIsPublic() != null ? request.getIsPublic() : 0)
                .setCollectCount(0);
        collectionFolderMapper.insert(folder);

        return folder.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteCollectionFolder(Long folderId) {
        Long currentUserId = ContextHolderUtils.getCurrentUserId();

        CollectionFolder folder = collectionFolderMapper.selectById(folderId);
        if (folder == null || !folder.getUserId().equals(currentUserId)) {
            throw new ClientException("收藏夹不存在或无权删除");
        }

        collectionFolderMapper.deleteById(folderId);
        return true;
    }

    @Override
    public List<CollectionFolderResponseDTO> getCollectionFolders() {
        Long currentUserId = ContextHolderUtils.getCurrentUserId();

        List<CollectionFolder> folders = collectionFolderMapper.selectList(
                new LambdaQueryWrapper<CollectionFolder>()
                        .eq(CollectionFolder::getUserId, currentUserId)
        );

        return folders.stream()
                .map(folder -> BeanUtil.copyProperties(folder, CollectionFolderResponseDTO.class))
                .collect(Collectors.toList());
    }

    @Override
    public IPage<ArticleListResponseDTO> getCollectedArticles(Integer current, Integer size, Long folderId) {
        // TODO: 实现收藏文章列表查询，需要联表查询文章表
        Page<ArticleListResponseDTO> page = new Page<>(current, size);
        // 暂时返回空页面
        return page;
    }
}
