package ch.unisg.tapas.auctionhouse.adapter.in.web;

import ch.unisg.tapas.auctionhouse.adapter.common.formats.AuctionHouseDiscoveryJsonRepresentation;
import ch.unisg.tapas.auctionhouse.application.port.in.AuctionHouseDiscoveryUseCase;
import ch.unisg.tapas.auctionhouse.domain.AuctionHouseDiscoveryInformation;

import java.util.List;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Controller that handles HTTP requests for the auction house discovery. This controller implements
 * the {@link AuctionHouseDiscoveryUseCase} use case using the {@link AuctionHouseDiscoveryCommand} command.
 */
@RestController
public class AuctionHouseDiscoveryWebController {
    private final AuctionHouseDiscoveryUseCase auctionHouseDiscoveryUseCase;

    public AuctionHouseDiscoveryWebController(AuctionHouseDiscoveryUseCase auctionHouseDiscoveryUseCase) {
        this.auctionHouseDiscoveryUseCase = auctionHouseDiscoveryUseCase;
    }

    @GetMapping(path="/discovery/", consumes = AuctionHouseDiscoveryJsonRepresentation.MEDIA_TYPE)
    public ResponseEntity<String> auctionHouseDiscovery() {
        List<AuctionHouseDiscoveryInformation> auctionHouseDiscoveryInformation = auctionHouseDiscoveryUseCase.auctionHouseDiscovery();

        ObjectMapper mapper = new ObjectMapper();
        ObjectNode response = mapper.createObjectNode();
        ArrayNode array = response.putArray("auctionHouseInfo");


        for (AuctionHouseDiscoveryInformation info : auctionHouseDiscoveryInformation) {
            array.add(mapper.valueToTree(new AuctionHouseDiscoveryJsonRepresentation(info)));
        }

        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add(HttpHeaders.CONTENT_TYPE, AuctionHouseDiscoveryJsonRepresentation.MEDIA_TYPE);

        return new ResponseEntity<>(response.toString(), responseHeaders, HttpStatus.OK);
    }
}
