package com.lingyue.document.service;

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.lingyue.document.entity.Document;
import com.lingyue.document.repository.DocumentRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * 文档服务（基础框架）
 */
@Service
@RequiredArgsConstructor
public class DocumentService {
    
    private final DocumentRepository documentRepository;
    
    /**
     * 根据ID获取文档
     */
    public Document getDocumentById(String documentId) {
        return documentRepository.selectById(documentId);
    }
    
    /**
     * 根据用户ID分页查询文档
     */
    public IPage<Document> getDocumentsByUserId(String userId, Page<Document> page) {
        LambdaQueryWrapper<Document> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Document::getUserId, userId);
        wrapper.orderByDesc(Document::getCreateTime);
        return documentRepository.selectPage(page, wrapper);
    }
    
    /**
     * 保存文档
     */
    public Document saveDocument(Document document) {
        if (document.getId() == null) {
            document.setId(java.util.UUID.randomUUID().toString().replace("-", ""));
            document.setCreateTime(new java.util.Date());
            documentRepository.insert(document);
        } else {
            // 检查是否已存在该记录
            Document existing = documentRepository.selectById(document.getId());
            if (existing == null) {
                // 如果不存在，执行插入
                document.setCreateTime(new java.util.Date());
                documentRepository.insert(document);
            } else {
                // 如果存在，执行更新
                document.setUpdateTime(new java.util.Date());
                documentRepository.updateById(document);
            }
        }
        return document;
    }
    
    /**
     * 删除文档
     */
    public void deleteDocument(String documentId) {
        documentRepository.deleteById(documentId);
    }
}
