package enea.lecservice.controllers;

import com.fasterxml.jackson.core.type.TypeReference;
import enea.lecservice.models.dto.BaseRequest;
import enea.lecservice.models.dto.ServiceResponse;
import enea.lecservice.models.dto.DataRequest;
import enea.lecservice.security.IUserInfoService;
import enea.lecservice.services.IDataService;
import enea.lecservice.utils.JacksonUtils;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;

import static org.springframework.http.HttpHeaders.CONTENT_LANGUAGE;

@RestController
@RequestMapping("data")
@RequiredArgsConstructor
@Log4j2
public class DataController {
    @NonNull IDataService dataService;
    @NonNull IUserInfoService userInfoService;

    @PostMapping( value = "getData", produces = MediaType.APPLICATION_JSON_VALUE)
    public ServiceResponse<Object> getData(@RequestHeader(value=CONTENT_LANGUAGE) String lang, Principal principal, @RequestBody DataRequest configuration) throws Exception {
        var userInfo = userInfoService.getUserInfo(principal);
        if (userInfo.isEmpty())
            throw new Exception("User not logged.");
        configuration.setToken(userInfo.get().getToken().getValue());
        configuration.setContentLanguage(lang);
        log.info(configuration.toString());
         
        return ServiceResponse.Success(JacksonUtils.fromJson(dataService.getData(configuration), new TypeReference<Object>( ) {
        }));
    }

    @GetMapping( value = "admin/getListOfFunctions", produces = MediaType.APPLICATION_JSON_VALUE)
    public String getListOfFunctions(@RequestHeader(value=CONTENT_LANGUAGE) String lang, Principal principal) throws Exception {
        var userInfo = userInfoService.getUserInfo(principal);
        if (userInfo.isEmpty())
            throw new Exception("User not logged.");
        return dataService.getListOfFunctions(BaseRequest.builder()
                .token(userInfo.get().getToken().getValue())
                .contentLanguage(lang)
                .build());
    }
    
    @GetMapping( value = "admin/clearListOfFunctions", produces = MediaType.APPLICATION_JSON_VALUE)
    public String clearListOfFunctions(@RequestHeader(value=CONTENT_LANGUAGE) String lang, Principal principal) throws Exception {
        var userInfo = userInfoService.getUserInfo(principal);
        if (userInfo.isEmpty())
            throw new Exception("User not logged.");
        return dataService.clearListOfFunctions(BaseRequest.builder()
                .token(userInfo.get().getToken().getValue())
                .contentLanguage(lang)
                .build());
    }
    
}
