package cn.reghao.tnb.auth.app.service;

import cn.reghao.jutil.jdk.security.RandomString;
import cn.reghao.tnb.auth.app.db.mapper.oauth.UserOauthAppMapper;
import cn.reghao.tnb.auth.app.db.mapper.oauth.ClientDetailsMapper;
import cn.reghao.tnb.auth.app.model.dto.OAuthAppDto;
import cn.reghao.tnb.auth.app.model.po.oauth.UserOauthApp;
import cn.reghao.tnb.auth.app.model.po.oauth.ClientDetails;
import cn.reghao.tnb.auth.app.security.form.AccountAuthToken;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author reghao
 * @date 2023-02-20 14:58:25
 */
@Service
public class OAuthAppService {
    private final ClientDetailsMapper clientDetailsMapper;
    private final UserOauthAppMapper userOauthAppMapper;
    private final AccountTokenService accountTokenService;

    public OAuthAppService(ClientDetailsMapper clientDetailsMapper,
                           UserOauthAppMapper userOauthAppMapper,
                           AccountTokenService accountTokenService) {
        this.clientDetailsMapper = clientDetailsMapper;
        this.userOauthAppMapper = userOauthAppMapper;
        this.accountTokenService = accountTokenService;
    }

    @Transactional(rollbackFor = Exception.class)
    public void create(OAuthAppDto oAuthAppDto) {
        AccountAuthToken authToken = accountTokenService.getAuthToken();
        long userId = authToken.getUserId();

        String appName = oAuthAppDto.getName();
        String description = oAuthAppDto.getDescription();
        String homeUrl = oAuthAppDto.getHomeUrl();
        String callbackUrl = oAuthAppDto.getCallbackUrl();

        String clientId = appName;
        String clientSecret = RandomString.getString(32);
        String resourceIds = "";
        String scope = "";
        String authorizedGrantTypes = "authorization_code,refresh_token";
        String autoapprove = "true";

        ClientDetails clientDetails = new ClientDetails(clientId, clientSecret, resourceIds, scope,
                authorizedGrantTypes, callbackUrl, autoapprove);
        UserOauthApp userOauthApp = new UserOauthApp(userId, appName, homeUrl, clientId);

        clientDetailsMapper.save(clientDetails);
        userOauthAppMapper.save(userOauthApp);
    }

    @Transactional(rollbackFor = Exception.class)
    public void delete(String clientId) {
        // TODO 撤销所有令牌
        clientDetailsMapper.deleteByClientId(clientId);
        userOauthAppMapper.deleteByClientId(clientId);
    }

    public List<ClientDetails> getAll() {
        long loginUser = accountTokenService.getAuthToken().getUserId();
        return clientDetailsMapper.findByOwner(loginUser);
    }

    public ClientDetails get(String clientId) {
        return clientDetailsMapper.findByClientId(clientId);
    }
}
