package de.votian.services.controller;

import de.votian.services.dto.StatisticsSummaryDto;
import de.votian.services.dto.UserSessionDto;
import de.votian.services.security.AccessControlService;
import de.votian.services.service.ViewDataService;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;

@RestController
@RequestMapping("/api/reporting")
public class ReportingController {

    private final ViewDataService viewDataService;
    private final AccessControlService accessControlService;

    public ReportingController(ViewDataService viewDataService,
                               AccessControlService accessControlService) {
        this.viewDataService = viewDataService;
        this.accessControlService = accessControlService;
    }

    @GetMapping("/statistics")
    public ResponseEntity<StatisticsSummaryDto> statistics(
            @RequestParam Long hqId,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate from,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate to,
            Authentication authentication) {
        UserSessionDto user = accessControlService.sessionUser(authentication);
        if (!accessControlService.canViewStatistics(user)) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
        }
        if (accessControlService.isCustomerUser(user)) {
            return ResponseEntity.ok(viewDataService.buildStatisticsSummaryForCostCenters(
                    user.getHeadquartersId(),
                    user.getAccessibleCostCenterIds(),
                    from,
                    to
            ));
        }
        if (!accessControlService.canAccessHeadquarters(user, hqId)) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
        }
        return ResponseEntity.ok(viewDataService.buildStatisticsSummary(hqId, from, to));
    }
}
