package ru.yandex.canvas.controllers;

import java.util.List;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import ru.yandex.canvas.configs.auth.AuthorizeBy;
import ru.yandex.canvas.model.ValidationError;
import ru.yandex.canvas.service.CreativesService;

import static ru.yandex.canvas.configs.auth.AuthorizeBy.AuthType.DIRECT_TOKEN;

/**
 * @author solovyev
 */
@RestController
@RequestMapping(value = "/rtbHost")

public class RtbHostController {

    private static final Logger logger = LoggerFactory.getLogger(RtbHostController.class);
    private final CreativesService creativesService;

    public RtbHostController(CreativesService creativesService) {
        this.creativesService = creativesService;
    }

    @AuthorizeBy({DIRECT_TOKEN})
    @PostMapping(value = "uploadCreatives")
    public ResponseEntity<?> uploadCreatives(@Valid @RequestBody final CreativesData creatives,
                                             final BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            logger.warn(bindingResult.getAllErrors().toString());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ValidationError("Invalid request"));
        }

        creativesService.exportToRTBHost(creativesService.fetchByIds(creatives.getIds()));

        return ResponseEntity.ok().build();
    }


    private static class CreativesData {

        @NotNull
        @Size(min = 1, max = 50)
        private List<Long> ids;

        public List<Long> getIds() {
            return ids;
        }

        public void setIds(List<Long> ids) {
            this.ids = ids;
        }

        @Override
        public String toString() {
            return "Creatives{" +
                    "ids=" + ids +
                    '}';
        }
    }
}
