package com.bytesw.bytebot.controller;

import com.bytesw.bytebot.service.provider.TwilioService;
import com.bytesw.xdf.exception.NotFoundException;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.log4j.Log4j2;
import com.twilio.exception.AuthenticationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.google.gson.Gson;

import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.Map;

@Log4j2
@RestController
@RequestMapping("/providers")
public class ProviderController {

    @Autowired
    private TwilioService twilioService;

    @Autowired
    private Gson gson;

    @ApiResponses(value={
            @ApiResponse(code=200, message = "OK"),
            @ApiResponse(code=400, message = "Bad Request. Datos de entrada inválido"),
            @ApiResponse(code=401, message = "Unauthorized. Credenciales erróneas"),
            @ApiResponse(code=404, message = "Not Found. Recursos no encontrados")
    })
    @RequestMapping(value="/twilio/messages/{sid_message}",method = {RequestMethod.DELETE})
    public ResponseEntity<String> deleteSensibleInfo(@ApiParam(value="sid_message",required = true) @PathVariable("sid_message") String sid_message,
        @ApiParam(value = "agent_id: Agente a cual eliminar su data sensible\n{\"agent_id\":1}",
        example = "{agent_id:1}",required = true) @NotNull @RequestBody(required = false) Map<String,Object> body){

        Map<String,Object> info = new HashMap<>();
        try {
            if (body == null) {
                log.info("Body Input Inválido");
                throw new ClassCastException("Input inválido");
            }
            info = twilioService.generateInfo(sid_message, body);
        }catch (ClassCastException e){
            return new ResponseEntity<>(e.getMessage(),HttpStatus.BAD_REQUEST);
        }catch(NotFoundException e){
            return new ResponseEntity<>(e.getMessage(),HttpStatus.NOT_FOUND);
        }catch (AuthenticationException e){
            return new ResponseEntity<>(e.getMessage(),HttpStatus.UNAUTHORIZED);
        }catch (InternalError e){
            return new ResponseEntity<>(e.getMessage(),HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return  new ResponseEntity<>(gson.toJson(info), HttpStatus.OK);
    }
}
