package com.yd.oss.service.service.impl;

import com.yd.common.exception.BusinessException;
import com.yd.oss.service.model.OssProvider;
import com.yd.oss.service.dao.OssProviderMapper;
import com.yd.oss.service.service.IOssProviderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 云存储服务商配置表 服务实现类
 * </p>
 *
 * @author zxm
 * @since 2025-08-22
 */

@Slf4j
@Primary
@Service
public class OssProviderServiceImpl extends ServiceImpl<OssProviderMapper, OssProvider> implements IOssProviderService {

    @Autowired
    private OssProviderMapper ossProviderMapper;

    /**
     * 获取默认的OSS提供商
     * @return
     */
    @Override
    public OssProvider getDefaultProvider() {
        OssProvider provider = ossProviderMapper.selectDefaultProvider();
        if (provider == null) {
            log.error("未找到默认的OSS提供商");
            throw new BusinessException("未找到默认的OSS提供商");
        }
        return provider;
    }

    /**
     * 根据名称获取OSS提供商
     * @param name
     * @return
     */
    @Override
    public OssProvider getProviderByName(String name) {
        OssProvider provider = ossProviderMapper.selectByName(name);
        if (provider == null) {
            log.error("未找到名为 {} 的OSS提供商", name);
            throw new BusinessException("未找到名为 " + name + " 的OSS提供商");
        }
        return provider;
    }

    /**
     * 根据ID获取OSS提供商
     * @param id
     * @return
     */
    @Override
    public OssProvider getProviderById(Long id) {
        OssProvider provider = ossProviderMapper.selectById(id);
        if (provider == null) {
            log.error("未找到ID为 {} 的OSS提供商", id);
            throw new BusinessException("未找到ID为 " + id + " 的OSS提供商");
        }
        return provider;
    }

    /**
     * 获取所有激活的OSS提供商
     * @return
     */
    @Override
    public List<OssProvider> getActiveProviders() {
        return ossProviderMapper.selectActiveProviders();
    }

    /**
     * 保存OSS提供商
     * @param provider
     * @return
     */
    @Override
    public boolean saveProvider(OssProvider provider) {
        LocalDateTime now = LocalDateTime.now();
        if (provider.getId() == null) {
            // 新增
            provider.setCreateTime(now);
            provider.setUpdateTime(now);
            return ossProviderMapper.insert(provider) > 0;
        } else {
            // 更新
            provider.setUpdateTime(now);
            return ossProviderMapper.updateById(provider) > 0;
        }
    }

    /**
     * 删除OSS提供商
     * @param id
     * @return
     */
    @Override
    public boolean deleteProvider(Long id) {
        return ossProviderMapper.deleteById(id) > 0;
    }
}
