package com.red.circle.other.infra.database.mongo.service.user.profile.impl;

import com.red.circle.other.domain.enums.ContactMode;
import com.red.circle.other.domain.enums.VipAbilityType;
import com.red.circle.other.infra.database.mongo.entity.user.profile.UserVipAbilitySetting;
import com.red.circle.other.infra.database.mongo.service.user.profile.UserVipAbilitySettingService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@RequiredArgsConstructor
public class UserVipAbilitySettingServiceImpl implements UserVipAbilitySettingService {

    private final MongoTemplate mongoTemplate;

    @Override
    public boolean isEnabled(Long userId, VipAbilityType abilityType) {
        UserVipAbilitySetting setting = mongoTemplate.findById(userId, UserVipAbilitySetting.class);
        if (setting == null) {
            // 默认值: 第一次开通 VIP 时，功能开关默认开启 true
            return true;
        }
        switch (abilityType) {
            case KICK_PREVENTION: return Boolean.TRUE.equals(setting.getKickPrevention());
            case MYSTERIOUS_INVISIBILITY: return Boolean.TRUE.equals(setting.getMysteriousInvisibility());
            case ANTI_BLOCK: return Boolean.TRUE.equals(setting.getAntiBlock());
            default: return false;
        }
    }

    @Override
    public ContactMode getContactMode(Long userId) {
        UserVipAbilitySetting setting = mongoTemplate.findById(userId, UserVipAbilitySetting.class);
        if (setting == null || setting.getContactMode() == null) {
            return ContactMode.EVERYONE;
        }
        return ContactMode.valueOf(setting.getContactMode());
    }

    @Override
    public void upsert(UserVipAbilitySetting setting) {
        setting.setUpdateTime(new Date());
        Query query = Query.query(Criteria.where("_id").is(setting.getUserId()));
        Update update = new Update()
                .set("contactMode", setting.getContactMode())
                .set("kickPrevention", setting.getKickPrevention())
                .set("mysteriousInvisibility", setting.getMysteriousInvisibility())
                .set("antiBlock", setting.getAntiBlock())
                .set("lastVipLevel", setting.getLastVipLevel())
                .set("updateTime", setting.getUpdateTime());
        mongoTemplate.upsert(query, update, UserVipAbilitySetting.class);
    }

    @Override
    public UserVipAbilitySetting findByUserId(Long userId) {
        return mongoTemplate.findById(userId, UserVipAbilitySetting.class);
        // 或者用 query:
        // return mongoTemplate.findOne(Query.query(Criteria.where("_id").is(userId)), UserVipAbilitySetting.class);
    }
}