package com.izouma.nineth.listener;

import com.izouma.nineth.domain.User;
import com.izouma.nineth.event.RegisterEvent;
import com.izouma.nineth.security.JwtTokenUtil;
import com.izouma.nineth.security.JwtUserFactory;
import com.izouma.nineth.service.UserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
@AllArgsConstructor
@RocketMQMessageListener(
        consumerGroup = "${general.register-group}",
        topic = "${general.register-topic}",
        consumeMode = ConsumeMode.ORDERLY)
@ConditionalOnProperty(value = "general.notify-server", havingValue = "false", matchIfMissing = true)
public class RegisterListener implements RocketMQListener<RegisterEvent> {
    private       UserService                   userService;
    private       RedisTemplate<String, Object> redisTemplate;
    private final JwtTokenUtil                  jwtTokenUtil;

    @Override
    public void onMessage(RegisterEvent registerEvent) {
        Map<String, Object> map = new HashMap<>();
        try {
            User user = userService.phoneRegister(registerEvent.getPhone(), registerEvent.getCode(),
                    registerEvent.getPassword(), registerEvent.getInviteCode(),
                    registerEvent.getInvitor(), registerEvent.getCollectionId());
            map.put("status", "success");
            map.put("data", user);
            map.put("token", jwtTokenUtil.generateToken(JwtUserFactory.create(user)));
            redisTemplate.opsForValue().set("register::" + registerEvent.getPhone(), map, Duration.ofSeconds(600));
        } catch (Exception e) {
            map.put("status", "fail");
            map.put("data", e.getMessage());
            redisTemplate.opsForValue().set("register::" + registerEvent.getPhone(), map, Duration.ofSeconds(600));
        }
    }
}
