package com.r11.tools.controller;

import com.r11.tools.mappers.RequestHistoryMapper;
import com.r11.tools.model.HistoryRequestModel;
import com.r11.tools.model.RequestHistory;
import com.r11.tools.model.RequestHistoryDTO;
import com.r11.tools.service.RequestHistoryService;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * It's the REST api for {@link RequestHistory}
 * @author Gabriel Modzelewski
 * @author Mikołaj Widła
 */
@RestController
@RequestMapping(path = "/api/event")
@AllArgsConstructor
@CrossOrigin(origins = "*")
public class RequestHistoryController {
    private final RequestHistoryService service;
    private final RequestHistoryMapper mapper;

    /**
     * Returns the list of Events in given time bracket.
     * The list of objects is received via {@link RequestHistoryDTO}, which contains time brackets,
     * as well as the key - uuid.
     * @param historyRequestModel EventRequestDto object that contains data needed to query the database
     * @return list of {@link RequestHistory}
     */
    @PostMapping
    public ResponseEntity<List<RequestHistoryDTO>> filterHistory(@RequestBody HistoryRequestModel historyRequestModel){
        return ResponseEntity.ok(
                service.getHistoryRecordsBetweenDatesAndByUUIDAndMessageId(historyRequestModel)
                        .stream()
                        .map(mapper::requestHistoryToRequestHistoryDTO)
                        .collect(Collectors.toList())
        );
    }

    /**
     * Returns the list of Events of last 24h from given date.
     * @param uuid unique id of message list
     * @param messageId unique id of message in message list
     * @return list of {@link RequestHistory}
     */
    @GetMapping(path = "/{uuid}/{messageId}")
    public ResponseEntity<List<RequestHistoryDTO>> getLastDay(@PathVariable UUID uuid,
                                                        @PathVariable Integer messageId){
        LocalDateTime requestTime = LocalDateTime.now();
        LocalDateTime dayBeforeRequest = requestTime.minusDays(1L);
        List<RequestHistoryDTO> requestHistory = service.getHistoryRecordsBetweenDatesAndByUUIDAndMessageId(
                HistoryRequestModel.builder()
                        .localDateTimeFrom(dayBeforeRequest)
                        .localDateTimeTo(requestTime)
                        .clientUUID(uuid)
                        .mockedResponseId(messageId)
                        .build()
        ).stream()
                .map(mapper::requestHistoryToRequestHistoryDTO)
                .collect(Collectors.toList());
        return ResponseEntity.ok(requestHistory);
    }
}

