package apiPackage;

import java.io.Serializable;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;
import javax.servlet.http.HttpSession;

import com.google.gson.JsonObject;

import apiClients.CrifApiClient;
import apiClients.ExperianApiClient;

@ManagedBean(name="experianCibilApiBean")
@ViewScoped
public class experianCibilApiBean implements Serializable {

    private String firstName;
    private String lastName;
    private String mobileNo;
    private String panNumber;
    private String cibilScore;
    private String cibilReport;
    private boolean showForm = true;
    private boolean showResult = false;

    // Getters and Setters
    public String getFirstName() { return firstName; }
    public void setFirstName(String firstName) { this.firstName = firstName; }

    public String getLastName() { return lastName; }
    public void setLastName(String lastName) { this.lastName = lastName; }

    public String getMobileNo() { return mobileNo; }
    public void setMobileNo(String mobileNo) { this.mobileNo = mobileNo; }

    public String getPanNumber() { return panNumber; }
    public void setPanNumber(String panNumber) { this.panNumber = panNumber; }

    public String getCibilScore() { return cibilScore; }
    public void setCibilScore(String cibilScore) { this.cibilScore = cibilScore; }

    public String getCibilReport() { return cibilReport; }
    public void setCibilReport(String cibilReport) { this.cibilReport = cibilReport; }

    public boolean isShowForm() { return showForm; }
    public void setShowForm(boolean showForm) { this.showForm = showForm; }

   

    public boolean isShowResult() { return showResult; }
    public void setShowResult(boolean showResult) { this.showResult = showResult; }

    public void fetchReport() {
        try {
            HitApi();
        } catch (Exception e) {
            FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_ERROR, "API Error", e.getMessage()));
            e.printStackTrace();
        }
        
//		      this.cibilScore = "750"; // Dummy
//		      this.cibilReport = "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf"; 
//		      this.showResult = true;
//		      this.showForm = false;
  	
    }
 
  

    
    public void HitApi() {
    	HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		String username=(String) ss.getAttribute("username");
		

    	
    	 UrlInfoBean urlInfoBean = new UrlInfoBean();
		 String client = urlInfoBean.getClientName();
		 System.out.println("client = " + client);

		 if (client == null || client.trim().length() == 0) {
			    FacesContext.getCurrentInstance().addMessage(null,
			        new FacesMessage(FacesMessage.SEVERITY_ERROR, "Configuration Error", "Client URL missing"));
			    return;
			}
			  
		 
        try {
            ExperianApiClient ex= new ExperianApiClient();
            JsonObject response = ex.callExperianApi(
                this.panNumber, this.firstName+" "+this.lastName, this.mobileNo,
                client, username
            );

            System.out.println("API Response: " + response);

            JsonObject firstItem = response.getAsJsonArray("track").get(0).getAsJsonObject();

            String message = getSafeString(firstItem, "message");
            System.out.println("Message: " + message);

            boolean status = firstItem.get("status").getAsBoolean();
            System.out.println("Status: " + status);

            if (status) {
                this.showResult = true;
                this.showForm = false;

                this.cibilScore = getSafeString(firstItem, "creditScore"); // check key name
                this.cibilReport = getSafeString(firstItem, "link");
            } else {
            	this.showResult = false;
            	this.showForm = true;

                FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_WARN, "Verification Failed", message));
            }
        } catch (Exception e) {
            FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_ERROR, "API Error", e.getMessage()));
            e.printStackTrace();
        }
    }


    public void resetFlow() {
        this.firstName = null;
        this.lastName = null;
        this.mobileNo = null;
        this.panNumber = null;
        this.cibilScore = null;
        this.cibilReport = null;
        this.showForm = true;
    
        this.showResult = false;
    }
   
    public  String getSafeString(JsonObject obj, String key) {
        if (obj.has(key) && !obj.get(key).isJsonNull()) {
            return obj.get(key).getAsString();
        }
        return null;
    }
    
	public void validatePan(FacesContext context, UIComponent component, Object value) throws ValidatorException {
	    String panValue = (String) value;

	    if (panValue == null || panValue.trim().isEmpty()) {
	        throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
	                "PAN number cannot be empty!", null));
	    }

	    
	    String panRegex = "[A-Z]{5}[0-9]{4}[A-Z]{1}";

	    if (!panValue.toUpperCase().matches(panRegex)) {
	        throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
	                "Invalid PAN format! Example: ABCDE1234F", null));
	    }
	}

	
   
}
