package com.erp.ai.service;

import com.erp.ai.dto.KnowledgeFileRequest;
import com.erp.ai.mapper.AiKnowledgeFileMapper;
import com.erp.ai.model.AiKnowledgeFile;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * AI 지식 파일 서비스.
 * RAG 라이브러리 + 커스텀 업로드.
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AiKnowledgeService {

    private final AiKnowledgeFileMapper knowledgeMapper;

    public List<AiKnowledgeFile> list(String category, String companyCode) {
        Map<String, Object> filters = new HashMap<>();
        if (category != null) filters.put("category", category);
        if (companyCode != null) filters.put("company_code", companyCode);
        return knowledgeMapper.list(filters);
    }

    public AiKnowledgeFile getById(long id) {
        return knowledgeMapper.getById(id);
    }

    @Transactional
    public AiKnowledgeFile create(KnowledgeFileRequest req, String userId, String companyCode) {
        AiKnowledgeFile f = new AiKnowledgeFile();
        f.setName(req.getName());
        f.setFile_name(req.getFile_name());
        f.setCategory(req.getCategory());
        f.setDescription(req.getDescription());
        f.setContent(req.getContent());
        f.setFile_size(req.getFile_size() != null ? req.getFile_size() : 0L);
        f.setMime_type(req.getMime_type());
        f.setCompany_code(companyCode);
        f.setCreated_by(userId);
        knowledgeMapper.insert(f);
        return knowledgeMapper.getById(f.getId());
    }

    @Transactional
    public AiKnowledgeFile update(long id, KnowledgeFileRequest req) {
        AiKnowledgeFile f = new AiKnowledgeFile();
        f.setId(id);
        f.setName(req.getName());
        f.setFile_name(req.getFile_name());
        f.setCategory(req.getCategory());
        f.setDescription(req.getDescription());
        f.setContent(req.getContent());
        f.setFile_size(req.getFile_size());
        f.setMime_type(req.getMime_type());
        knowledgeMapper.update(f);
        return knowledgeMapper.getById(id);
    }

    @Transactional
    public void delete(long id) {
        knowledgeMapper.delete(id);
    }
}
