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

import com.eshore.gringotts.web.domain.base.repository.SimpleRepository;
import com.eshore.gringotts.web.domain.base.service.SimpleService;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * 上传服务
 *
 * @author lanyuanxiaoyao
 * @date 2024-11-21
 */
@Service
public class DataFileService extends SimpleService<DataFile, Long> {
    private static final Logger logger = LoggerFactory.getLogger(DataFileService.class);

    private final DataFileRepository dataFileRepository;
    private final UserService userService;

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

    @Override
    protected SimpleRepository<DataFile, Long> repository() {
        return dataFileRepository;
    }

    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("更新文件信息失败，请重新上传");
        }
    }
}
