package enea.lecservice.services;

import com.fasterxml.jackson.core.type.TypeReference;
import enea.lecservice.dto.Form;
import enea.lecservice.models.dto.ServiceResponse;
import enea.lecservice.utils.FileUtils;
import enea.lecservice.utils.JacksonUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;

@Log4j2
@Service
@Profile("!dev")
@RequiredArgsConstructor
public class FormService implements IFormService{
    @Value("${data.api.baseurl}")
    private String baseUrl;

    @Override
    public ServiceResponse<Object> get(String code, String token) {
        String url = String.format("%s%s",
                baseUrl,
                "getTableMetadata"
        );

        var headers = new org.springframework.http.HttpHeaders();
        headers.add(HttpHeaders.AUTHORIZATION, token);

        /*var map = new HashMap<String, Object>();
        map.put("tableName", code);*/
        var entity = new HttpEntity<>(code, headers);

        /*String result = new RestTemplate().getForObject(url, String.class, entity);*/
        String result = new RestTemplate().postForObject(url, entity, String.class);
        log.info(result);
        return ServiceResponse.Success(JacksonUtils.fromJson(result, new TypeReference<Object>( ) {}));
    }

    @Override
    public ServiceResponse<Object> post(Form form) {
        String url = String.format("%s%s",
                baseUrl,
                "forms"
        );

        var headers = new org.springframework.http.HttpHeaders();
        headers.add(HttpHeaders.AUTHORIZATION, form.getToken());

        var map = new HashMap<String, Object>();
        map.put("code", form.getCode());
        map.put("description", form.getDescription());
        map.put("fields", form.getFields());
        map.put("id", form.getId());

        var entity = new HttpEntity<>(map, headers);

        log.info(JacksonUtils.toJson(map));
        String result = new RestTemplate().postForObject(url, entity, String.class);
        log.info(result);
        return ServiceResponse.Success(result);
    }
}
