package com.alttd.altitudeweb.controllers.team;

import com.alttd.altitudeweb.api.TeamApi;
import com.alttd.altitudeweb.services.limits.RateLimit;
import com.alttd.altitudeweb.setup.Connection;
import com.alttd.altitudeweb.database.Databases;
import com.alttd.altitudeweb.database.luckperms.Player;
import com.alttd.altitudeweb.database.luckperms.TeamMemberMapper;
import com.alttd.altitudeweb.model.PlayerDto;
import com.alttd.altitudeweb.model.TeamMembersDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RateLimit(limit = 30, timeValue = 1, timeUnit = TimeUnit.MINUTES)
public class TeamApiController implements TeamApi {

    @Override
    public ResponseEntity<TeamMembersDto> getTeamMembers(String group) {
        TeamMembersDto teamMemberDtos = new TeamMembersDto();
        CompletableFuture<List<Player>> playerGroupFuture = new CompletableFuture<>();
        Connection.getConnection(Databases.LUCK_PERMS)
                .runQuery(sqlSession -> {
                    log.debug("Loading team members for group {}", group);
                    try {
                        List<Player> players = sqlSession.getMapper(TeamMemberMapper.class).getTeamMembers("group." + group);
                        playerGroupFuture.complete(players);
                    } catch (Exception e) {
                        log.error("Failed to load team members for group {}", group, e);
                        playerGroupFuture.completeExceptionally(e);
                    }
                });
        List<Player> join = playerGroupFuture.join();
        join.forEach(player -> teamMemberDtos.add(new PlayerDto(player.username(), player.uuid().toString())));
        return ResponseEntity.ok().body(teamMemberDtos);
    }
}
