package json_package;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.primefaces.json.JSONObject;

public class CibilApiMethod implements Serializable {

    public static HttpURLConnection connection;

    // Inner class to hold score and link
    public static class CibilResponse 
    {
        private String score;
        private String link;

        public CibilResponse(String score, String link) {
            this.score = score;
            this.link = link;
        }

        public String getScore() {
            return score;
        }

        public String getLink() {
            return link;
        }
    }

    public int checkApiBalance(String apiService) {
        return 0;
    }

    public CibilResponse hitExperian(String name, String pan, String mobile, String userId) 
    {
        String apiUrl = "https://kyc-api.surepass.io/api/v1/credit-report-experian/fetch-report-pdf";
        return fetchCibilReport(apiUrl, name, pan, mobile, null);
    }

    public CibilResponse hitCibil(String name, String pan, String mobile, String userId, String gender) 
    {
        String apiUrl = "https://kyc-api.surepass.io/api/v1/credit-report-cibil/fetch-report-pdf";
        return fetchCibilReport(apiUrl, name, pan, mobile, gender);
    }

    private CibilResponse fetchCibilReport(String apiUrl, String name, String pan, String mobile, String gender) 
    {
        HttpURLConnection connection = null;
        String score = "N/A";
        String link = "";

        try {
            URL url = new URL(apiUrl);
           //System.out.println("apiurl"+apiUrl);
           
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setReadTimeout(15000);
            connection.setConnectTimeout(15000);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("Authorization", "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJmcmVzaCI6ZmFsc2UsImlhdCI6MTc0NDcyMDg5NiwianRpIjoiMTdhYzRkNDItOWQ2Yy00NzI4LTliNGMtOGUxMzhlYTM2MTAyIiwidHlwZSI6ImFjY2VzcyIsImlkZW50aXR5IjoiZGV2Lmd3aXRwbEBzdXJlcGFzcy5pbyIsIm5iZiI6MTc0NDcyMDg5NiwiZXhwIjoyMzc1NDQwODk2LCJlbWFpbCI6Imd3aXRwbEBzdXJlcGFzcy5pbyIsInRlbmFudF9pZCI6Im1haW4iLCJ1c2VyX2NsYWltcyI6eyJzY29wZXMiOlsidXNlciJdfX0.uYktPC1ihvxgetxQ3901G9eraPCwC4M3I4ENrlyeWJs"); // Replace with real token
            connection.setDoOutput(true);

            JSONObject jsonBody = new JSONObject();
            jsonBody.put("name", name);
            jsonBody.put("consent", "Y");
            jsonBody.put("mobile", mobile);
            jsonBody.put("pan", pan);
            if (gender != null) {
                jsonBody.put("gender", gender);
            }
            
            //System.out.println(jsonBody);

            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonBody.toString().getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            int responseCode = connection.getResponseCode();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    responseCode > 299 ? connection.getErrorStream() : connection.getInputStream()));

            StringBuilder content = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line);
            }
            reader.close();

            //System.out.println("Response: " + content);

            JSONObject jsonResponse = new JSONObject(content.toString());
            JSONObject data = jsonResponse.optJSONObject("data");

            if (data != null) {
                score = data.optString("credit_score", "N/A");
                link = data.optString("credit_report_link", "");

               // System.out.println("Credit Score: " + score);
               // System.out.println("PDF Link: " + link);

                FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_INFO, "CIBIL fetched successfully!", "Score: " + score));
            } else {
                FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_WARN, "No data found", "Check API response."));
            }

        } catch (Exception e) {
            e.printStackTrace();
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error fetching CIBIL", e.getMessage()));
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }

        return new CibilResponse(score, link);
    }
}
