package de.htwsaar.webshop.controller;

import de.htwsaar.webshop.model.MonthlyCatModel;
import de.htwsaar.webshop.service.SessionService;
import de.htwsaar.webshop.service.StatisticsService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

import static de.htwsaar.webshop.config.ControllerPathConfig.STATISTICS_REVENUE;
import static de.htwsaar.webshop.config.ControllerPathConfig.STATISTICS_VOLUME;
import static de.htwsaar.webshop.config.ParameterConfig.PARAM_EMAIL;
import static de.htwsaar.webshop.config.ParameterConfig.PARAM_SESSION;
import static de.htwsaar.webshop.util.LoggerUtil.logRequest;

@RestController
@Slf4j
public class StatisticsController {

    private final StatisticsService statisticsService;
    private final SessionService sessionService;

    public StatisticsController(StatisticsService statisticsService, SessionService sessionService) {
        this.statisticsService = statisticsService;
        this.sessionService = sessionService;
    }

    @RequestMapping(value = STATISTICS_VOLUME, method = RequestMethod.GET, produces = "application/json")
    public ResponseEntity<MonthlyCatModel<Integer>> getMonthlySalesVolume(HttpServletRequest request,
                                                                          @RequestParam(value = PARAM_SESSION) UUID session,
                                                                          @RequestParam(value = PARAM_EMAIL) String email) {
        logRequest(request);
        if (!sessionService.isAdmin(session, email)) {
            log.warn("Invalid session requesting Admin {}", session);
            return ResponseEntity.status(403).build();
        }
        return ResponseEntity.ok(statisticsService.getSalesVolume());
    }

    @RequestMapping(value = STATISTICS_REVENUE, method = RequestMethod.GET, produces = "application/json")
    public ResponseEntity<MonthlyCatModel<Integer>> getMonthlyRevenue(HttpServletRequest request,
                                                                      @RequestParam(value = PARAM_SESSION) UUID token,
                                                                      @RequestParam(value = PARAM_EMAIL) String email) {
        logRequest(request);
        if (!sessionService.isAdmin(token, email)) {
            log.warn("Invalid session requesting Admin {}", token);
            return ResponseEntity.status(403).build();
        }
        return ResponseEntity.ok(statisticsService.getSalesRevenue());
    }

}
