package de.avatic.lcc.controller.configuration;

import de.avatic.lcc.dto.error.CalculationJobDumpDTO;
import de.avatic.lcc.repositories.error.DumpRepository;
import de.avatic.lcc.repositories.pagination.SearchQueryPagination;
import jakarta.validation.constraints.Min;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/dumps")
public class CalculationDumpController {

    private final DumpRepository dumpRepository;

    public CalculationDumpController(DumpRepository dumpRepository) {
        this.dumpRepository = dumpRepository;
    }

    @GetMapping({"/dump/{id}", "/dump/{id}/"})
    @PreAuthorize("hasRole('SERVICE')")
    public ResponseEntity<CalculationJobDumpDTO> getDump(@PathVariable Integer id) {
        return ResponseEntity.ok(dumpRepository.getDump(id));
    }

    @GetMapping({"/dump/", "/dump"})
    @PreAuthorize("hasRole('SERVICE')")
    public ResponseEntity<List<CalculationJobDumpDTO>> listDumps(
            @RequestParam(defaultValue = "20") @Min(1) int limit,
            @RequestParam(defaultValue = "1") @Min(1) int page) {

        var dump = dumpRepository.listDumps(new SearchQueryPagination(page, limit));

        return ResponseEntity.ok()
                .header("X-Total-Count", String.valueOf(dump.getTotalElements()))
                .header("X-Page-Count", String.valueOf(dump.getTotalPages()))
                .header("X-Current-Page", String.valueOf(page))
                .body(dump.toList());
    }
}
