package cashfree;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Scanner;
import java.util.UUID;
import org.json.simple.JSONObject;
import main_package.DataBaseConnection;

public class CashfreeSubscriptionPaymentService {

    private static String CLIENT_ID = null;
    private static String CLIENT_SECRET = null;
    private static final String BASE_URL = "https://api.cashfree.com/pg";
    private static final String API_VERSION = "2026-01-01";
    private static final String PROVIDER_CODE = "cashfree-enatch";
    private static boolean credentialsLoaded = false;

    public static synchronized boolean fetchApiDetailsDB() {
        if (credentialsLoaded && !isEmpty(CLIENT_ID) && !isEmpty(CLIENT_SECRET)) return true;
        String query = "SELECT keyid, keySecret FROM api_keys WHERE provider_code = ? LIMIT 1";
        try (Connection conn = DataBaseConnection.JAVAConnection();
             PreparedStatement ps = conn.prepareStatement(query)) {
            ps.setString(1, PROVIDER_CODE);
            try (ResultSet rs = ps.executeQuery()) {
                if (rs.next()) {
                    CLIENT_ID = rs.getString("keyid");
                    CLIENT_SECRET = rs.getString("keySecret");
                    if (!isEmpty(CLIENT_ID) && !isEmpty(CLIENT_SECRET)) {
                        credentialsLoaded = true;
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static String raisePayment(String subscriptionId, String paymentId, double amount, String scheduleDate) {
        if (isEmpty(subscriptionId)) return createErrorJson("subscriptionId is required");
        if (isEmpty(paymentId)) return createErrorJson("paymentId is required");
        if (amount <= 0) return createErrorJson("payment amount must be greater than zero");
        if (isEmpty(scheduleDate)) return createErrorJson("scheduleDate is required");

        PaymentRecord existing = findPaymentInTracking(paymentId);
        if (existing != null && !isEmpty(existing.cfPaymentId)) {
            return createExistingPaymentJson(paymentId, existing.cfPaymentId, existing.paymentStatus);
        }

        JSONObject payload = new JSONObject();
        payload.put("subscription_id", subscriptionId);
        payload.put("payment_id", paymentId);
        payload.put("payment_type", "CHARGE");
        payload.put("payment_amount", amount);
        payload.put("payment_schedule_date", scheduleDate);

        return executeHttpPost(BASE_URL + "/subscriptions/pay", payload.toString(), UUID.randomUUID().toString());
    }

    public static String createControlledNotification(String notificationId, String paymentId, String subscriptionId, double amount) {
        if (isEmpty(notificationId)) return createErrorJson("notificationId is required");
        if (isEmpty(paymentId)) return createErrorJson("paymentId is required");
        if (isEmpty(subscriptionId)) return createErrorJson("subscriptionId is required");
        if (amount <= 0) return createErrorJson("payment amount must be greater than zero");

        PaymentRecord payment = findPaymentInTracking(paymentId);
        if (payment == null || isEmpty(payment.cfPaymentId)) {
            return createErrorJson("Charge has not been raised for payment_id: " + paymentId);
        }

        JSONObject payload = new JSONObject();
        payload.put("notification_id", notificationId);
        payload.put("payment_amount", amount);
        payload.put("payment_id", paymentId);
        payload.put("subscription_id", subscriptionId);

        return executeHttpPost(BASE_URL + "/subscriptions/pay/controlled/notify-mandate", payload.toString(), UUID.randomUUID().toString());
    }

    public static String createControlledExecution(String executionId, String paymentId) {
        if (isEmpty(executionId)) return createErrorJson("executionId is required");
        if (isEmpty(paymentId)) return createErrorJson("paymentId is required");

        JSONObject payload = new JSONObject();
        payload.put("execution_id", executionId);
        payload.put("payment_id", paymentId);

        return executeHttpPost(BASE_URL + "/subscriptions/pay/controlled/execute-mandate", payload.toString(), UUID.randomUUID().toString());
    }

    public static String fetchAllPayments(String subscriptionId) {
        if (isEmpty(subscriptionId)) return createErrorJson("subscriptionId is required");
        return executeHttpGet(BASE_URL + "/subscriptions/" + subscriptionId + "/payments");
    }

    private static PaymentRecord findPaymentInTracking(String paymentId) {
        if (isEmpty(paymentId)) return null;
        String sql = "SELECT payment_id, cf_payment_id, payment_status FROM cashfree_emi_tracking WHERE payment_id = ? LIMIT 1";
        try (Connection conn = DataBaseConnection.JAVAConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, paymentId);
            try (ResultSet rs = ps.executeQuery()) {
                if (rs.next()) {
                    PaymentRecord record = new PaymentRecord();
                    record.paymentId = rs.getString("payment_id");
                    record.cfPaymentId = rs.getString("cf_payment_id");
                    record.paymentStatus = rs.getString("payment_status");
                    return record;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static class PaymentRecord {
        String paymentId, cfPaymentId, paymentStatus;
    }

    public static String fetchPayment(String subscriptionId, String paymentId) {
        if (isEmpty(subscriptionId)) return createErrorJson("subscriptionId is required");
        if (isEmpty(paymentId)) return createErrorJson("paymentId is required");
        return executeHttpGet(BASE_URL + "/subscriptions/" + subscriptionId + "/payments/" + paymentId);
    }

    private static String executeHttpPost(String urlStr, String jsonBody, String idempotencyKey) {
        if (!fetchApiDetailsDB()) return createErrorJson("Cashfree API credentials not configured");
        HttpURLConnection conn = null;
        try {
            conn = (HttpURLConnection) new URL(urlStr).openConnection();
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setDoOutput(true);
            setCommonHeaders(conn);
            conn.setRequestProperty("x-request-id", UUID.randomUUID().toString());
            if (!isEmpty(idempotencyKey)) conn.setRequestProperty("x-idempotency-key", idempotencyKey);

            try (OutputStream os = conn.getOutputStream()) {
                os.write(jsonBody.getBytes(StandardCharsets.UTF_8));
            }
            return readResponse(conn);
        } catch (Exception e) {
            e.printStackTrace();
            return createErrorJson(e);
        } finally {
            if (conn != null) conn.disconnect();
        }
    }

    private static String executeHttpGet(String urlStr) {
        if (!fetchApiDetailsDB()) return createErrorJson("Cashfree API credentials not configured");
        HttpURLConnection conn = null;
        try {
            conn = (HttpURLConnection) new URL(urlStr).openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            setCommonHeaders(conn);
            conn.setRequestProperty("x-request-id", UUID.randomUUID().toString());
            return readResponse(conn);
        } catch (Exception e) {
            e.printStackTrace();
            return createErrorJson(e);
        } finally {
            if (conn != null) conn.disconnect();
        }
    }

    private static void setCommonHeaders(HttpURLConnection conn) {
        conn.setRequestProperty("x-client-id", CLIENT_ID);
        conn.setRequestProperty("x-client-secret", CLIENT_SECRET);
        conn.setRequestProperty("x-api-version", API_VERSION);
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("Content-Type", "application/json");
    }

    private static String readResponse(HttpURLConnection conn) {
        try {
            int responseCode = conn.getResponseCode();
            InputStream inputStream = (responseCode >= 200 && responseCode < 300) ? conn.getInputStream() : conn.getErrorStream();
            if (inputStream == null) return "{\"http_status\":" + responseCode + "}";

            try (Scanner scanner = new Scanner(inputStream, StandardCharsets.UTF_8.name())) {
                String response = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
                return (response == null || response.trim().isEmpty()) ? "{\"http_status\":" + responseCode + "}" : response;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return createErrorJson(e);
        }
    }

    private static String createExistingPaymentJson(String paymentId, String cfPaymentId, String paymentStatus) {
        JSONObject json = new JSONObject();
        json.put("payment_id", paymentId);
        json.put("cf_payment_id", cfPaymentId);
        json.put("payment_status", paymentStatus != null ? paymentStatus : "INITIALIZED");
        json.put("payment_type", "CHARGE");
        json.put("existing_payment", true);
        return json.toString();
    }

    private static String createErrorJson(Exception e) {
        return createErrorJson(e.getMessage() != null ? e.getMessage() : "Unknown error");
    }

    private static String createErrorJson(String message) {
        if (message == null) message = "Unknown error";
        message = message.replace("\\", "\\\\").replace("\"", "\\\"").replace("\r", " ").replace("\n", " ");
        return "{\"error\":\"" + message + "\"}";
    }

    private static boolean isEmpty(String value) {
        return value == null || value.trim().isEmpty();
    }
}