package org.agt.module.infra.api.file;

import cn.hutool.core.util.StrUtil;
import org.agt.framework.common.pojo.CommonResult;
import org.agt.module.infra.api.file.dto.FileCreateReqDTO;
import org.agt.module.infra.service.file.FileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RestController;

import jakarta.annotation.Resource;

import static org.agt.framework.common.pojo.CommonResult.success;

@RestController // 提供 RESTful API 接口，给 Feign 调用
@Validated
public class FileApiImpl implements FileApi {

    private static final Logger log = LoggerFactory.getLogger(FileApiImpl.class);
    @Resource
    private FileService fileService;

    @Override
    public CommonResult<String> createFile(FileCreateReqDTO createReqDTO) {
        return success(fileService.createFile(createReqDTO.getContent(), createReqDTO.getName(),
                createReqDTO.getDirectory(), createReqDTO.getType()));
    }

    @Override
    public CommonResult<byte[]> getFileContent(String url) {
        byte[] content = null;
        try {
            String path = StrUtil.subAfter(url, "/get/", false);
            String configId = StrUtil.subBetween(url, "/file/", "/get/");
            content = fileService.getFileContent(Long.valueOf(configId), path);
        } catch (Exception e) {
            log.error("get file content error {}", url, e);
        }
        return success(content);
    }

}
