package top.tqx.demo_1.service.impl;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.tqx.demo_1.entity.CollectionFile;
import top.tqx.demo_1.mapper.CollectionFileMapper;
import top.tqx.demo_1.service.CollectionFileService;

import java.util.List;

@Service
@RequiredArgsConstructor
@Slf4j
public class CollectionFileServiceImpl implements CollectionFileService {

    private final CollectionFileMapper collectionFileMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CollectionFile saveOrUpdate(String collectionName, String docName, Long fileId, String filePath, String docType) {
        CollectionFile existing = collectionFileMapper.findByCollectionAndDocName(collectionName, docName);
        
        if (existing != null) {
            existing.setFileId(fileId);
            existing.setFilePath(filePath);
            existing.setDocType(docType);
            existing.setStatus(1);
            collectionFileMapper.updateById(existing);
            log.info("更新向量库文件关联: collection={}, docName={}", collectionName, docName);
            return existing;
        }
        
        CollectionFile collectionFile = new CollectionFile();
        collectionFile.setCollectionName(collectionName);
        collectionFile.setDocName(docName);
        collectionFile.setFileId(fileId);
        collectionFile.setFilePath(filePath);
        collectionFile.setDocType(docType);
        collectionFile.setStatus(1);
        collectionFileMapper.insert(collectionFile);
        log.info("创建向量库文件关联: collection={}, docName={}", collectionName, docName);
        return collectionFile;
    }

    @Override
    public List<CollectionFile> findByDocName(String docName) {
        return collectionFileMapper.findByDocNameWithFileInfo(docName);
    }

    @Override
    public List<CollectionFile> findByCollectionName(String collectionName) {
        return collectionFileMapper.findByCollectionName(collectionName);
    }

    @Override
    public CollectionFile findByCollectionAndDocName(String collectionName, String docName) {
        return collectionFileMapper.findByCollectionAndDocName(collectionName, docName);
    }

    @Override
    public CollectionFile findByFileId(Long fileId) {
        return collectionFileMapper.findByFileId(fileId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        collectionFileMapper.deleteById(id);
        log.info("删除向量库文件关联: id={}", id);
    }
}
