package com.lanyuanxiaoyao.service.ai.knowledge.service;

import club.kingon.sql.builder.SqlBuilder;
import cn.hutool.core.util.IdUtil;
import com.lanyuanxiaoyao.service.ai.knowledge.entity.vo.DataFileVO;
import com.lanyuanxiaoyao.service.common.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author lanyuanxiaoyao
 * @version 20250527
 */
@Service
public class DataFileService {
  private static final Logger log = LoggerFactory.getLogger(DataFileService.class);
  private static final String DATA_FILE_TABLE_NAME = Constants.DATABASE_NAME + ".service_ai_file";

  private final JdbcTemplate template;

  public DataFileService(JdbcTemplate template) {
    this.template = template;
  }

  public DataFileVO downloadFile(Long id) {
    return template.queryForObject(
        SqlBuilder.select("id", "filename", "size", "md5", "path", "type")
            .from(DATA_FILE_TABLE_NAME)
            .whereEq("id", "?")
            .precompileSql(),
        (rs, row) -> {
          DataFileVO vo = new DataFileVO();
          vo.setId(String.valueOf(rs.getLong(1)));
          vo.setFilename(rs.getString(2));
          vo.setSize(rs.getLong(3));
          vo.setMd5(rs.getString(4));
          vo.setPath(rs.getString(5));
          vo.setType(rs.getString(6));
          return vo;
        },
        id
    );
  }

  @Transactional(rollbackFor = Exception.class)
  public Long initialDataFile(String filename) {
    long id = IdUtil.getSnowflakeNextId();
    template.update(
        SqlBuilder.insertInto(DATA_FILE_TABLE_NAME, "id", "filename")
            .values()
            .addValue("?", "?")
            .precompileSql(),
        id,
        filename
    );
    return id;
  }

  @Transactional(rollbackFor = Exception.class)
  public void updateDataFile(Long id, String path, Long size, String md5, String type) {
    template.update(
        SqlBuilder.update(DATA_FILE_TABLE_NAME)
            .set("size", "?")
            .addSet("md5", "?")
            .addSet("path", "?")
            .addSet("type", "?")
            .whereEq("id", "?")
            .precompileSql(),
        size,
        md5,
        path,
        type,
        id
    );
  }

  public static final class DataFileNotFoundException extends RuntimeException {
    public DataFileNotFoundException() {
      super("文件未找到，请重新上传");
    }
  }

  public static final class UpdateDataFileFailedException extends RuntimeException {
    public UpdateDataFileFailedException() {
      super("更新文件信息失败，请重新上传");
    }
  }
}
