package com.samsung.user.controller;

import com.samsung.authentication.Account;
import com.samsung.common.entity.JwtResponse;
import com.samsung.common.util.JwtUtil;
import com.samsung.user.UserService;
import com.samsung.user.dto.UserInfoDto;
import com.samsung.user.entity.User;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TokenController {

    private final UserService userService;

    private final JwtUtil jwtUtil;

    public TokenController(UserService userService, JwtUtil jwtUtil) {
        this.userService = userService;
        this.jwtUtil = jwtUtil;
    }

    @Operation(summary = "토큰 갱신")
    @PutMapping("/auth/users/user-token")
    public JwtResponse updateToken(@Parameter(description = "사용자 정보") @RequestBody UserInfoDto userInfoDto) {

        User user = Account.currentUser();
        assert user != null;
        if (ObjectUtils.isNotEmpty(userInfoDto)) {
            String timeZoneId = userInfoDto.getTimeZoneId();
            String timeZoneCode = userInfoDto.getTimeZoneCode();
            String language = userInfoDto.getLanguage();
            if (StringUtils.isNoneBlank(timeZoneId, timeZoneCode)) {
                user.setTimeZoneId(timeZoneId);
                user.setTimeZoneCode(timeZoneCode);
            }
            if (StringUtils.isNotBlank(language)) {
                user.setLanguage(language);
            }
        }

        JwtResponse jwtResponse = new JwtResponse(jwtUtil.generateToken(user), user.getUserId());
        user.setJwt(jwtResponse.getJwtToken().split("\\.")[2]);

        userService.updateUser(user);

        return jwtResponse;
    }
}
