package com.njcn.rdms.module.system.api.file;

import com.njcn.rdms.framework.common.pojo.CommonResult;
import com.njcn.rdms.framework.common.util.object.BeanUtils;
import com.njcn.rdms.module.system.api.file.dto.FileContentCreateReqDTO;
import com.njcn.rdms.module.system.api.file.dto.FileRespDTO;
import com.njcn.rdms.module.system.dal.dataobject.file.FileDO;
import com.njcn.rdms.module.system.service.file.FileService;
import io.swagger.v3.oas.annotations.Hidden;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RestController;

import static com.njcn.rdms.framework.common.pojo.CommonResult.success;

@RestController
@Validated
@Hidden
public class FileApiImpl implements FileApi {

    @Resource
    private FileService fileService;

    @Override
    public CommonResult<FileRespDTO> getFileByUrl(String url) {
        FileDO file = fileService.getFileByUrl(url);
        return success(BeanUtils.toBean(file, FileRespDTO.class));
    }

    @Override
    public CommonResult<FileRespDTO> getFile(Long id) {
        FileDO file = fileService.getFile(id);
        return success(BeanUtils.toBean(file, FileRespDTO.class));
    }

    @Override
    public CommonResult<byte[]> getFileContent(Long id) {
        try {
            FileDO file = fileService.getFile(id);
            if (file == null) {
                return success(null);
            }
            return success(fileService.getFileContent(file.getConfigId(), file.getPath()));
        } catch (Exception ex) {
            throw new IllegalStateException("读取文件内容失败", ex);
        }
    }

    @Override
    public CommonResult<Long> createFileByContent(FileContentCreateReqDTO reqDTO) {
        FileDO file = fileService.createFile(reqDTO.getContent(), reqDTO.getName(), reqDTO.getDirectory(), reqDTO.getType());
        return success(file.getId());
    }

}
