package com.psg.dlsysinfo.dl_sysinfo_server.controller;

import com.psg.dlsysinfo.dl_sysinfo_server.entity.Cve;
import com.psg.dlsysinfo.dl_sysinfo_server.dto.CveDTO;
import org.springframework.data.domain.PageImpl;
import java.util.stream.Collectors;
import com.psg.dlsysinfo.dl_sysinfo_server.entity.CveMatchResult;
import com.psg.dlsysinfo.dl_sysinfo_server.repository.CveRepository;
import com.psg.dlsysinfo.dl_sysinfo_server.service.VulnerabilityScannerService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/public/vulnerabilities")
public class PublicVulnerabilityController {

    private final CveRepository cveRepository;

    public PublicVulnerabilityController(CveRepository cveRepository) {
        this.cveRepository = cveRepository;
    }

    @GetMapping
    public ResponseEntity<Page<CveDTO>> searchPublicCVEs(
            @RequestParam(required = false) String search,
            @PageableDefault(size = 25, sort = "lastModifiedDate", direction = Sort.Direction.DESC)
            Pageable pageable
    ) {
        Page<Cve> cvePage = cveRepository.findFiltered(search, pageable);

        Page<CveDTO> dtoPage = new PageImpl<>(
                cvePage.getContent().stream()
                        .filter(cve -> {
                            String desc = cve.getDescription();
                            return desc == null || !desc.trim().equalsIgnoreCase("Rejected reason: Not used");
                        })
                        .map(CveDTO::new)
                        .collect(Collectors.toList()),
                pageable,
                cvePage.getTotalElements()
        );

        return ResponseEntity.ok(dtoPage);
    }

}
