package de.avatic.taric.controller;

import de.avatic.taric.model.Certificate;
import de.avatic.taric.repository.CertificateRepository;
import de.avatic.taric.repository.CertificateTypeRepository;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
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")
@Tag(name = "Certificates", description = "API endpoints for managing and retrieving certificates")
public class CertificateController {

    private final CertificateRepository certificateRepository;
    private final CertificateTypeRepository certificateTypeRepository;

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

    @Operation(
            summary = "Get certificates",
            description = "Retrieves all certificates or filters by certificate type code. Returns an empty list if the certificate type code is not found."
    )
    @ApiResponses(value = {
            @ApiResponse(
                    responseCode = "200",
                    description = "Successfully retrieved certificates",
                    content = @Content(mediaType = "application/json", schema = @Schema(implementation = Certificate.class))
            )
    })
    @GetMapping
    public Iterable<Certificate> getCertificates(
            @Parameter(description = "Optional certificate type code to filter certificates by type")
            @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();
    }
}