package enea.lecservice.controllers;

import enea.lecservice.dto.Form;
import enea.lecservice.models.dto.ServiceResponse;
import enea.lecservice.security.IUserInfoService;
import enea.lecservice.services.IFormService;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;

@RestController
@RequiredArgsConstructor
public class FormController {
    @NonNull IUserInfoService userInfoService;
    @NonNull IFormService formService;

    @GetMapping( value = "forms/{code}", produces = MediaType.APPLICATION_JSON_VALUE)
    public ServiceResponse<Object> getForm(@PathVariable String code, Principal principal) throws Exception {
        var userInfo = userInfoService.getUserInfo(principal);
        if (userInfo.isEmpty())
            throw new Exception("User not logged.");
        return formService.get(code, userInfo.get().getToken().getValue());
    }

    @PostMapping( value = "forms/save", produces = MediaType.APPLICATION_JSON_VALUE)
    public ServiceResponse<Object> postForm(Principal principal, @RequestBody Form form) throws Exception {
        var userInfo = userInfoService.getUserInfo(principal);
        if (userInfo.isEmpty())
            throw new Exception("User not logged.");
        form.setToken(userInfo.get().getToken().getValue());
        return formService.post(form);
    }
}
