package org.qinan.safetyeval.domain.service;

import org.qinan.safetyeval.domain.entity.FileStorage;
import org.qinan.safetyeval.domain.exception.BizException;
import org.qinan.safetyeval.domain.exception.ErrorCode;
import org.qinan.safetyeval.domain.gateway.ResourceGateway;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 文件存储领域服务
 * <p>
 * 协调 OSS 存储操作与本地数据库维护管理，
 * 确保文件存储/删除时同步更新 filestorage 表。
 * </p>
 *
 * @author safety-eval
 */
@Service
public class FileStorageDomainService {

    @javax.annotation.Resource
    private ResourceGateway resourceGateway;

    /**
     * 保存文件元信息到数据库
     */
    public FileStorage saveResource(FileStorage fileStorage) {
        if (fileStorage == null) {
            throw new BizException(ErrorCode.FILE_UPLOAD_EMPTY);
        }
        return resourceGateway.save(fileStorage);
    }

    /**
     * 批量保存文件元信息
     */
    public List<FileStorage> saveResourceBatch(List<FileStorage> fileStorages) {
        if (fileStorages == null || fileStorages.isEmpty()) {
            throw new BizException(ErrorCode.FILE_UPLOAD_EMPTY);
        }
        return resourceGateway.saveBatch(fileStorages);
    }

    /**
     * 根据ID获取文件元信息
     */
    public FileStorage getResource(Integer id) {
        FileStorage fileStorage = resourceGateway.get(id);
        if (fileStorage == null) {
            throw new BizException(ErrorCode.FILE_NOT_FOUND);
        }
        return fileStorage;
    }

    /**
     * 根据文件名获取文件元信息
     */
    public FileStorage getResourceByFilename(String filename) {
        FileStorage fileStorage = resourceGateway.getByFilename(filename);
        if (fileStorage == null) {
            throw new BizException(ErrorCode.FILE_NOT_FOUND);
        }
        return fileStorage;
    }

    /**
     * 删除文件元信息
     */
    public void deleteResource(Integer id) {
        FileStorage fileStorage = resourceGateway.get(id);
        if (fileStorage == null) {
            throw new BizException(ErrorCode.FILE_NOT_FOUND);
        }
        resourceGateway.delete(id);
    }

    /**
     * 批量删除文件元信息
     */
    public void deleteResourceBatch(List<Integer> ids) {
        if (ids == null || ids.isEmpty()) {
            return;
        }
        resourceGateway.deleteBatch(ids);
    }

    /**
     * 获取所有文件列表
     */
    public List<FileStorage> listAllResources() {
        return resourceGateway.listAll();
    }

    /**
     * 根据创建者获取文件列表
     */
    public List<FileStorage> listResourcesByCreator(String creatorUid) {
        return resourceGateway.listByCreator(creatorUid);
    }
}
