package com.eshore.gringotts.web.domain.upload.service;

import com.eshore.gringotts.web.domain.base.service.SimpleServiceSupport;
import com.eshore.gringotts.web.domain.upload.entity.DataFile;
import com.eshore.gringotts.web.domain.upload.repository.DataFileRepository;
import com.eshore.gringotts.web.domain.user.entity.User;
import com.eshore.gringotts.web.domain.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 上传服务
 *
 * @author lanyuanxiaoyao
 * @date 2024-11-21
 */
@Slf4j
@Service
public class DataFileService extends SimpleServiceSupport<DataFile> {
    private final DataFileRepository dataFileRepository;
    private final UserService userService;

    public DataFileService(DataFileRepository dataFileRepository, UserService userService) {
        super(dataFileRepository, userService);
        this.dataFileRepository = dataFileRepository;
        this.userService = userService;
    }

    public DataFile detail(String id) {
        if (id == null) {
            return null;
        }
        return detail(Long.valueOf(id));
    }

    public Long initialDataFile(String filename) {
        DataFile dataFile = new DataFile();
        dataFile.setFilename(filename);
        User loginUser = userService.currentLoginUser();
        dataFile.setCreatedUser(loginUser);
        dataFile.setModifiedUser(loginUser);
        return dataFileRepository.save(dataFile).getId();
    }

    public void updateDataFile(Long id, String path, Long size, String md5) {
        DataFile dataFile = dataFileRepository.findById(id).orElseThrow(UpdateDataFileFailedException::new);
        dataFile.setSize(size);
        dataFile.setMd5(md5);
        dataFile.setPath(path);
        User loginUser = userService.currentLoginUser();
        dataFile.setModifiedUser(loginUser);
        dataFileRepository.save(dataFile);
    }

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

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