package com.vaessl.app.search;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.vaessl.app.shared.ServiceItem;
import com.vaessl.app.shared.SessionKeys;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;

@RestController
@RequiredArgsConstructor
public class SearchController {

    private final SearchService searchService;

    /**
     * Executes a paged search against the requested service. Returns {@code 401 Unauthorized} if
     * there is no active session.
     */
    @PostMapping("/search")
    public ResponseEntity<PagedSearchResponse<ServiceItem>> search(
            @Valid @RequestBody SearchRequest request,
            @PageableDefault(size = 20) Pageable pageable, HttpServletRequest httpReq) {
        HttpSession session = httpReq.getSession(false);
        if (session == null
                || session.getAttribute(SessionKeys.connectionId(request.serviceType())) == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }

        Page<ServiceItem> result = searchService.search(request, pageable);

        return ResponseEntity.ok(PagedSearchResponse.from(result));
    }
}
