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

import cn.meowrain.aioj.backend.blogservice.dao.entity.Draft;
import cn.meowrain.aioj.backend.blogservice.dto.req.DraftSaveRequestDTO;
import cn.meowrain.aioj.backend.blogservice.dto.resp.DraftResponseDTO;
import cn.meowrain.aioj.backend.blogservice.service.DraftService;
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.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;

/**
 * 草稿箱服务实现类
 *
 * @author AIOJ
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class DraftServiceImpl extends ServiceImpl<Draft, Draft> implements DraftService {

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

        Draft draft;
        if (request.getId() != null) {
            // 更新现有草稿
            draft = this.getById(request.getId());
            if (draft == null || !draft.getUserId().equals(currentUserId)) {
                throw new ClientException("草稿不存在或无权修改");
            }

            draft.setTitle(request.getTitle())
                    .setContent(request.getContent())
                    .setCategoryId(request.getCategoryId())
                    .setCoverImage(request.getCoverImage())
                    .setAutoSave(request.getAutoSave() != null ? request.getAutoSave() : 0)
                    .setUpdateTime(new Date());

            this.updateById(draft);
        } else {
            // 创建新草稿
            draft = new Draft()
                    .setUserId(currentUserId)
                    .setTitle(request.getTitle())
                    .setContent(request.getContent())
                    .setCategoryId(request.getCategoryId())
                    .setCoverImage(request.getCoverImage())
                    .setAutoSave(request.getAutoSave() != null ? request.getAutoSave() : 0);
            this.save(draft);
        }

        return draft.getId();
    }

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

        Draft draft = this.getById(draftId);
        if (draft == null || !draft.getUserId().equals(currentUserId)) {
            throw new ClientException("草稿不存在或无权删除");
        }

        this.removeById(draftId);
        return true;
    }

    @Override
    public DraftResponseDTO getDraftById(Long draftId) {
        Long currentUserId = ContextHolderUtils.getCurrentUserId();

        Draft draft = this.getById(draftId);
        if (draft == null || !draft.getUserId().equals(currentUserId)) {
            return null;
        }

        return BeanUtil.copyProperties(draft, DraftResponseDTO.class);
    }

    @Override
    public IPage<DraftResponseDTO> getDraftList(Integer current, Integer size) {
        Long currentUserId = ContextHolderUtils.getCurrentUserId();

        Page<Draft> page = new Page<>(current, size);
        IPage<Draft> draftPage = this.lambdaQuery()
                .eq(Draft::getUserId, currentUserId)
                .orderByDesc(Draft::getUpdateTime)
                .page(page);

        Page<DraftResponseDTO> resultPage = new Page<>(draftPage.getCurrent(), draftPage.getSize(), draftPage.getTotal());
        resultPage.setRecords(draftPage.getRecords().stream()
                .map(draft -> BeanUtil.copyProperties(draft, DraftResponseDTO.class))
                .collect(java.util.stream.Collectors.toList()));

        return resultPage;
    }

    @Override
    public DraftResponseDTO getLatestDraft() {
        Long currentUserId = ContextHolderUtils.getCurrentUserId();

        Draft draft = this.lambdaQuery()
                .eq(Draft::getUserId, currentUserId)
                .eq(Draft::getAutoSave, 1)
                .orderByDesc(Draft::getUpdateTime)
                .last("LIMIT 1")
                .one();

        if (draft == null) {
            return null;
        }

        return BeanUtil.copyProperties(draft, DraftResponseDTO.class);
    }
}
