package apiClients;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonReader;

import main_package.DataBaseMethodTaheer;

import java.io.StringReader;

public class CibilApiClient
{
    private static final String CIBIL_API_URL = "https://gwitapi.in/SOFT/api/v1/credit-report/crif/fetch-pdf-report";
    private static final String CIBIL_SCORE_URL = "https://gwitapi.in/SOFT/api/v1/verify/experian/check-credit-score";
    
    private static final String CIBIL_API_KEY = new DataBaseMethodTaheer().fetchAPIKeyAndSecretByCibilType("gwitapis", "keyid");
    private static final String CIBIL_API_SECRET = new DataBaseMethodTaheer().fetchAPIKeyAndSecretByCibilType("gwitapis", "keySecret");


    
    public JsonObject callCibilApi(String firstName, String lastName, String mobile, String pan, String aadhaarNumber, 
    							   String consent, String reportType) throws Exception
    {
        URL url = new URL(CIBIL_API_URL);
        
        if (reportType.equalsIgnoreCase("score")) 
		{
        	url = new URL(CIBIL_SCORE_URL);
		}
		else
		{
			url = new URL(CIBIL_API_URL);
		}

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        conn.setRequestMethod("POST");

        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Accept", "application/json");
        
        conn.setRequestProperty("x-api-key", CIBIL_API_KEY);
        conn.setRequestProperty("x-api-secret", CIBIL_API_SECRET);

        conn.setDoOutput(true);
        conn.setConnectTimeout(30000);
        conn.setReadTimeout(60000);


        JsonObject request = new JsonObject();

        if (reportType.equalsIgnoreCase("score")) 
		{
        	request.addProperty("name", firstName);
            request.addProperty("mobile", mobile);
		}
		else
		{
			request.addProperty("first_name", firstName);
	        request.addProperty("last_name", lastName);
	        request.addProperty("mobile", mobile);
	        request.addProperty("pan", pan);
	        request.addProperty("aadhaar_number", aadhaarNumber);
	        request.addProperty("consent", consent);
		}

        String requestBody = request.toString();

        System.out.println("CIBIL API Request:");
        System.out.println(requestBody);

        try (OutputStream os = conn.getOutputStream())
        {
            byte[] input = requestBody.getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
            os.flush();
        }

        int responseCode = conn.getResponseCode();

        System.out.println("CIBIL API Response Code: " + responseCode);


        InputStream inputStream;

        if (responseCode >= 200 && responseCode < 300)
        {
            inputStream = conn.getInputStream();
        }
        else
        {
            inputStream = conn.getErrorStream();
        }


        StringBuilder response = new StringBuilder();

        if (inputStream != null)
        {
            try (BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)))
            {
                String line;

                while ((line = in.readLine()) != null)
                {
                    response.append(line);
                }
            }
        }

        String responseStr = response.toString().trim();

        System.out.println("CIBIL API Raw Response:");
        System.out.println(responseStr);

        if (responseStr.isEmpty())
        {
            throw new Exception("Empty response received from CIBIL API. HTTP Code: " + responseCode);
        }

        JsonReader reader = new JsonReader(new StringReader(responseStr));

        reader.setLenient(true);

        return JsonParser.parseReader(reader).getAsJsonObject();
    }
    
    
    
    public String getSafeString(JsonObject obj, String key)
    {
        if (obj != null && obj.has(key) && !obj.get(key).isJsonNull())
        {
            return obj.get(key).getAsString();
        }

        return "";
    }
    
}