package com.games.gateway.rpc;

import com.alibaba.fastjson.JSON;
import com.games.gateway.domain.ServiceAuthRegist;
import com.games.gateway.domain.ServiceAuthRegisterRequest;
import com.games.gateway.utils.AesEncodeUtil;
import com.games.gateway.utils.AuthCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

@Slf4j
@RestController
public class AuthRegisterApi {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private AuthCache authCache;

    private static final String SECRET_KEY = "l5lUstfWcb3GlWqiiHJKVLKTSvwJSqrT";


    @RequestMapping("/")
    public Mono<String> root() {
        return Mono.just("success");
    }


    @RequestMapping("/api/gateway/auth/register")
    public Mono<String> authRegister(@RequestBody ServiceAuthRegisterRequest registerRequest) {
        try {
            String payload = AesEncodeUtil.decrypt(registerRequest.getContent(), SECRET_KEY);
            log.info("刷新 授权信息:{}", payload);

            ServiceAuthRegist serviceAuthRegist = JSON.parseObject(payload, ServiceAuthRegist.class);

            //覆盖
            String redisKey = "gateway:auth:" + serviceAuthRegist.getApplicationName();
            log.info("设置redis{}",  JSON.toJSONString(serviceAuthRegist));
            redisTemplate.opsForValue().set(redisKey, JSON.toJSONString(serviceAuthRegist));
            authCache.cache(redisKey, serviceAuthRegist);

        } catch (Exception e) {
            e.printStackTrace();
            log.error("出现上报异常",e);
        }
        return Mono.just("success");
    }

}
