package com.codenetworkz.blog.externalcall;

import com.codenetworkz.blog.config.RestTemplateConfig;
import com.codenetworkz.blog.web.dtos.FileUploadResponse;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
public class ExternalCallFileServiceImpl implements ExternalCallFileService {

  private final RestTemplateConfig restTemplateConfig;

  @Value("${service.file.url}")
  private String fileUploadUrl;

    ExternalCallFileServiceImpl(RestTemplateConfig restTemplateConfig) {
        this.restTemplateConfig = restTemplateConfig;
    }


    @Override
    public String upload(MultipartFile file) throws FileUploadException {
        String url = fileUploadUrl + "/uploadFile";

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        // Build request body
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("file", file.getResource());
        body.add("appName", "Blog");

        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

        FileUploadResponse uploadResponse = restTemplateConfig.getRestTemplate().postForObject(url, requestEntity, FileUploadResponse.class);
        if (uploadResponse!=null) {
           return uploadResponse.getFileCode();
        }
       throw new FileUploadException("Could not upload file");
    }

    @Override
    public MultipartFile download(String fileCode) throws IOException {
        String url = fileUploadUrl + "/downloadFile/"+fileCode;
        MultipartFile file = restTemplateConfig.getRestTemplate().getForObject(url, MultipartFile.class);
        if (file!=null) {
           return file;
        }
        throw new FileUploadException("Could not upload file");
    }

    @Override
    public String delete(String fileCode) throws FileUploadException {
        String url = fileUploadUrl + "/uploadFile";

        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json");
        // Add any additional headers you need
        HttpEntity<Object> requestEntity = new HttpEntity<>(fileCode, headers);

        ResponseEntity<String> response = restTemplateConfig.getRestTemplate().exchange(url, HttpMethod.DELETE, requestEntity, String.class, fileCode);
        return response.getBody();
    }
}
