package com.pluralsight.protectivetechnology.auditlogger.controller;

import com.pluralsight.protectivetechnology.auditlogger.dto.Resource;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Base64;

@RestController
@Slf4j
public class ResourceController {

    @SneakyThrows
    @PostMapping("/resources")
    public ResponseEntity<String> createResource(@RequestBody Resource resource, HttpServletRequest request) {
        String authentication = request.getHeader("authorization").substring("Basic".length()).trim();
        String decodedAuthentication = new String(Base64.getDecoder().decode(authentication));
        String user = decodedAuthentication.split(":")[0];

        String remoteAddress = request.getRemoteAddr();

        log.info("{}@{},{},create,{}", user, remoteAddress, resource.getResourceType(), resource.getName());
        return ResponseEntity.status(HttpStatus.CREATED)
                .build();
    }
}
