package de.avatic.taric.controller;

import de.avatic.taric.model.Certificate;
import de.avatic.taric.repository.CertificateRepository;
import de.avatic.taric.repository.CertificateTypeRepository;
import org.springframework.data.jdbc.core.mapping.AggregateReference;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/api/v1/certificates")
public class CertificateController {

    private final CertificateRepository certificateRepository;
    private final CertificateTypeRepository certificateTypeRepository;

    public CertificateController(CertificateRepository certificateRepository, CertificateTypeRepository certificateTypeRepository) {
        this.certificateRepository = certificateRepository;
        this.certificateTypeRepository = certificateTypeRepository;
    }

    @GetMapping
    public Iterable<Certificate> getCertificates(@RequestParam(required = false) String certificateTypeCode) {

        if (certificateTypeCode != null) {
            return certificateTypeRepository.findByCertificateTypeCode(certificateTypeCode).map(type -> certificateRepository.findByCertificateType(AggregateReference.to(type.getId()))).orElse(List.of());
        }

        return certificateRepository.findAll();
    }
}
