package enea.lecservice.controllers;

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

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

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

import java.security.Principal;


@RestController
@RequiredArgsConstructor
public class RegisterController {
    @NonNull
    protected IRegisterService service;
    
    @NonNull
    protected IUserInfoService userInfoService;

    @PostMapping("/register")
    public ServiceResponse<Object> register(@RequestHeader(value=CONTENT_LANGUAGE) String lang, @RequestBody LocalUserDTO model) {
        return ServiceResponse.Success(JacksonUtils.fromJson(service.register(model, lang), new TypeReference<Object>() {}));
    }

    @GetMapping("/listCommunities")
    public String communities(@RequestHeader(value=CONTENT_LANGUAGE) String lang) {
    	
        return service.getCommunities(BaseRequest.builder().contentLanguage(lang).build());
    }

    @PostMapping(value = "/account/activate")
    public ServiceResponse<Object> activateAccount(@RequestHeader(value=CONTENT_LANGUAGE) String lang, @RequestBody ActivateRequest request) {
        return ServiceResponse.Success(JacksonUtils.fromJson(service.activate(request, lang), new TypeReference<>() {}));
    }
    
    @PostMapping("/update")
    public ServiceResponse<Object> update(@RequestHeader(value=CONTENT_LANGUAGE) String lang, @RequestBody LocalUserDTO model, Principal principal) {
    	 var userInfo = userInfoService.getUserInfo(principal);
         if (userInfo.isEmpty())
             return ServiceResponse.Error("No user specified.");
        return ServiceResponse.Success(JacksonUtils.fromJson(service.update(model, lang, userInfo.get().getToken().getValue()), new TypeReference<Object>() {}));
    }
    
    @PostMapping("/updatePassword")
    public ServiceResponse<String> updatePasssword(@RequestHeader(value=CONTENT_LANGUAGE) String lang, @RequestBody LocalUserDTO model, Principal principal) {
    	  var userInfo = userInfoService.getUserInfo(principal);
          if (userInfo.isEmpty())
              return ServiceResponse.Error("No user specified.");
        return ServiceResponse.Success(JacksonUtils.fromJson(service.updatePassword(model, lang, userInfo.get().getToken().getValue()), new TypeReference<String>() {}));
    }
    
}
