package com.alttd.altitudeweb.controllers.site;

import com.alttd.altitudeweb.api.SiteApi;
import com.alttd.altitudeweb.controllers.data_from_auth.AuthenticatedUuid;
import com.alttd.altitudeweb.model.StaffPlaytimeDto;
import com.alttd.altitudeweb.model.StaffPlaytimeListDto;
import com.alttd.altitudeweb.model.VoteDataDto;
import com.alttd.altitudeweb.model.VoteStatsDto;
import com.alttd.altitudeweb.services.limits.RateLimit;
import com.alttd.altitudeweb.services.site.StaffPtService;
import com.alttd.altitudeweb.services.site.VoteService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RestController;

import java.time.Instant;
import java.time.OffsetDateTime;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequiredArgsConstructor
@RateLimit(limit = 2, timeValue = 10, timeUnit = TimeUnit.SECONDS)
public class SiteController implements SiteApi {

    private final VoteService voteService;
    private final AuthenticatedUuid authenticatedUuid;
    private final StaffPtService staffPtService;

    @Override
    @RateLimit(limit = 1, timeValue = 1, timeUnit = TimeUnit.SECONDS, key = "getStaffPlaytime")
    public ResponseEntity<StaffPlaytimeListDto> getStaffPlaytime(OffsetDateTime from, OffsetDateTime to) {
        Optional<List<StaffPlaytimeDto>> staffPlaytimeDto = staffPtService.getStaffPlaytime(from.toInstant(), to.toInstant());
        if (staffPlaytimeDto.isEmpty()) {
             return ResponseEntity.noContent().build();
        }
        StaffPlaytimeListDto staffPlaytimeListDto = new StaffPlaytimeListDto();
        staffPlaytimeListDto.addAll(staffPlaytimeDto.get());
        return ResponseEntity.ok(staffPlaytimeListDto);
    }

    @Override
    @RateLimit(limit = 5, timeValue = 1, timeUnit = TimeUnit.MINUTES, key = "getVoteStats")
    public ResponseEntity<VoteDataDto> getVoteStats() {
        UUID uuid = authenticatedUuid.getAuthenticatedUserUuid();
        Optional<VoteDataDto> optionalVoteDataDto = voteService.getVoteStats(uuid);
        if (optionalVoteDataDto.isEmpty()) {
            return ResponseEntity.noContent().build();
        }
        VoteDataDto voteDataDto = optionalVoteDataDto.get();
        return ResponseEntity.ok(voteDataDto);
    }
}
