package ovh.herisson.Clyde.Services;

import org.springframework.stereotype.Service;
import ovh.herisson.Clyde.Tables.*;
import java.util.Date;

@Service
public class AuthenticatorService {

    private final TokenService tokenService;
    private final UserService userService;
    private final InscriptionService inscriptionService;

    public AuthenticatorService(TokenService tokenService, UserService userService, InscriptionService inscriptionService){
        this.tokenService = tokenService;
        this.userService = userService;
        this.inscriptionService = inscriptionService;
    }

    public User getUserFromToken(String token){
        return tokenService.getUserFromToken(token);
    }


    public String login(String identifier, String password, Date expirationDate){
        User user = userService.getUser(identifier);
        if (user == null){return null;}
        if (!userService.checkPassword(user,password)){return null;}
        String token = tokenService.generateNewToken();
        tokenService.saveToken(new Token(user, token,expirationDate));
        return token;
    }

    public InscriptionRequest register(InscriptionRequest inscriptionRequest) {
        inscriptionRequest.setState(RequestState.Pending);
        return inscriptionService.save(inscriptionRequest);
    }

    public boolean isNotIn(Role[] roles, String token){
        if (token == null)
            return true;

        User poster = getUserFromToken(token);
        if (poster == null) return true;

        for (Role r:roles){
            if (poster.getRole() == r)
                return false;
        }
        return true;
    }
}

