package de.avatic.lcc.controller.users;

import de.avatic.lcc.dto.users.GroupContainerDTO;
import de.avatic.lcc.dto.users.GroupDTO;
import de.avatic.lcc.repositories.pagination.SearchQueryResult;
import de.avatic.lcc.service.users.GroupService;
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;

/**
 * REST controller for handling group-related operations.
 * Provides endpoints for retrieving and updating group information.
 */
@RestController
@RequestMapping("/api/groups")
public class GroupController {

    private final GroupService groupService;

    public GroupController(GroupService groupService) {
        this.groupService = groupService;
    }

    /**
     * Retrieves a paginated list of groups based on the provided limit and page parameters.
     * Also includes pagination metadata in response headers.
     *
     * @param limit The maximum number of groups to fetch per page. Defaults to 20.
     * @param page  The index of the page to retrieve. Defaults to 0 (first page).
     * @return A ResponseEntity containing the list of groups and pagination headers.
     */
    @GetMapping({"/", ""})
    @PreAuthorize("hasAnyRole('RIGHT-MANAGEMENT', 'SERVICE')")
    public ResponseEntity<GroupContainerDTO> listGroups(@RequestParam(defaultValue = "20") @Min(1) int limit,
                                                        @RequestParam(defaultValue = "1") @Min(1) int page) {

        SearchQueryResult<GroupDTO> groups = groupService.listGroups(page, limit);

        var container = new GroupContainerDTO();
        container.setGroups(groups.toList());

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

}
