package com.psg.dlsysinfo.dl_sysinfo_server.controller;

import com.psg.dlsysinfo.dl_sysinfo_server.dto.DeviceVulnerabilityDTO;
import com.psg.dlsysinfo.dl_sysinfo_server.entity.Cve;
import com.psg.dlsysinfo.dl_sysinfo_server.repository.CveRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/vuln/cves")
@RequiredArgsConstructor
public class VulnerabilityController {

    private final CveRepository cveRepository;

    @GetMapping("/lookup")
    public ResponseEntity<List<DeviceVulnerabilityDTO>> lookupCves(
            @RequestParam List<String> cveIds
    ) {
        List<Cve> cves = cveRepository.findAllById(cveIds);

        List<DeviceVulnerabilityDTO> results = cves.stream()
                .map(cve -> new DeviceVulnerabilityDTO(
                        cve.getId(),
                        cve.getDescription(),          // 👉 using description as title
                        cve.getSeverity(),
                        cve.getCvssScore(),
                        cve.getPublishedDate(),         // 📅 pull publishedDate
                        cve.getLastModifiedDate()       // 🔥 pull lastModifiedDate
                ))
                .toList();

        return ResponseEntity.ok(results);
    }


    @GetMapping("/all")
    public ResponseEntity<Page<Cve>> getAllCves(
            @RequestParam(required = false) String search,
            @PageableDefault(size = 25) Pageable pageable
    ) {
        return ResponseEntity.ok(cveRepository.findFiltered(search, pageable));
    }
}
