package cashfree;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;

import org.primefaces.json.JSONObject;

import main_package.DataBaseConnection;

public class EmiExecutionScheduler {

    /**
     * Executes UPI controlled payments on EMI due date.
     *
     * Flow:
     *
     * T-1:
     *      raisePayment()
     *      createControlledNotification()
     *
     * T-0:
     *      createControlledExecution()
     *
     * eNACH does NOT come here.
     */
    public void executeNotifiedUpiEmis() {

        LocalDate today =
                LocalDate.now();

        String sql =
                "SELECT " +
                "    id, " +
                "    loan_no, " +
                "    installment_no, " +
                "    subscription_id, " +
                "    payment_id, " +
                "    cf_payment_id, " +
                "    notification_id, " +
                "    cf_notification_id, " +
                "    amount, " +
                "    due_date, " +
                "    notification_status " +
                "FROM cashfree_emi_tracking " +
                "WHERE status = 'NOTIFIED_PENDING_COOLOFF' " +
                "AND LOWER(payment_group) = 'upi' " +
                "AND due_date = ? " +
                "AND notification_at <= DATE_SUB(NOW(), INTERVAL 24 HOUR)";

        try (Connection conn =
                     DataBaseConnection.JAVAConnection();
             PreparedStatement ps =
                     conn.prepareStatement(sql)) {

            ps.setString(
                    1,
                    today.toString());

            try (ResultSet rs =
                         ps.executeQuery()) {

                while (rs.next()) {

                    long trackingId =
                            rs.getLong("id");

                    String loanNo =
                            rs.getString("loan_no");

                    long installmentNo =
                            rs.getLong("installment_no");

                    String subscriptionId =
                            rs.getString("subscription_id");

                    String paymentId =
                            rs.getString("payment_id");

                    String notificationStatus =
                            rs.getString("notification_status");

                    try {

                        /*
                         * ----------------------------------------------
                         * Basic validation
                         * ----------------------------------------------
                         */
                        if (paymentId == null ||
                            paymentId.trim().isEmpty()) {

                            updateExecutionFailure(
                                    conn,
                                    trackingId,
                                    "EXECUTION_FAILED",
                                    "Missing payment_id");

                            continue;
                        }

                        if (subscriptionId == null ||
                            subscriptionId.trim().isEmpty()) {

                            updateExecutionFailure(
                                    conn,
                                    trackingId,
                                    "EXECUTION_FAILED",
                                    "Missing subscription_id");

                            continue;
                        }

                        /*
                         * ----------------------------------------------
                         * Notification should already be accepted.
                         *
                         * Example Cashfree response:
                         *
                         * notification_status = INITIALIZED
                         * ----------------------------------------------
                         */
                        if (notificationStatus == null ||
                            notificationStatus.trim().isEmpty()) {

                            updateExecutionFailure(
                                    conn,
                                    trackingId,
                                    "EXECUTION_FAILED",
                                    "Notification status is missing");

                            continue;
                        }

                        /*
                         * ----------------------------------------------
                         * Generate execution ID
                         * ----------------------------------------------
                         */
                        String executionId =
                                "EXEC_"
                                + paymentId;

                        /*
                         * ----------------------------------------------
                         * Create controlled execution
                         * ----------------------------------------------
                         */
                        String executionResponse;

                        try {

                            executionResponse =
                                    CashfreeSubscriptionPaymentService
                                            .createControlledExecution(
                                                    executionId,
                                                    paymentId);

                        } catch (Exception apiException) {

                            updateExecutionFailure(
                                    conn,
                                    trackingId,
                                    "EXECUTION_FAILED",
                                    apiException.getMessage());

                            continue;
                        }

                        /*
                         * ----------------------------------------------
                         * Parse response
                         * ----------------------------------------------
                         */
                        JSONObject executionJson;

                        try {

                            executionJson =
                                    new JSONObject(
                                            executionResponse);

                        } catch (Exception jsonException) {

                            updateExecutionResponse(
                                    conn,
                                    trackingId,
                                    executionId,
                                    null,
                                    "EXECUTION_FAILED",
                                    executionResponse);

                            continue;
                        }

                        String returnedExecutionId =
                                executionJson.optString(
                                        "execution_id",
                                        executionId);

                        String cfExecutionId =
                                executionJson.optString(
                                        "cf_execution_id",
                                        null);

                        String executionStatus =
                                executionJson.optString(
                                        "execution_status",
                                        null);

                        String paymentStatus =
                                executionJson.optString(
                                        "payment_status",
                                        null);

                        /*
                         * ----------------------------------------------
                         * Check execution response
                         * ----------------------------------------------
                         */
                        if (returnedExecutionId == null ||
                            returnedExecutionId.trim().isEmpty()) {

                            updateExecutionResponse(
                                    conn,
                                    trackingId,
                                    executionId,
                                    cfExecutionId,
                                    "EXECUTION_FAILED",
                                    executionResponse);

                            continue;
                        }

                        /*
                         * ----------------------------------------------
                         * Execution initiated successfully
                         * ----------------------------------------------
                         */
                        updateExecutionSuccess(
                                conn,
                                trackingId,
                                returnedExecutionId,
                                cfExecutionId,
                                executionStatus,
                                paymentStatus,
                                executionResponse);

                        System.out.println(
                                "UPI execution initiated successfully. "
                                + "Loan No: "
                                + loanNo
                                + ", EMI: "
                                + installmentNo
                                + ", Payment ID: "
                                + paymentId);

                    } catch (Exception emiException) {

                        System.err.println(
                                "Error executing UPI EMI. "
                                + "Loan No: "
                                + loanNo
                                + ", EMI: "
                                + installmentNo
                                + ", Error: "
                                + emiException.getMessage());

                        emiException.printStackTrace();

                        try {

                            updateExecutionFailure(
                                    conn,
                                    trackingId,
                                    "EXECUTION_FAILED",
                                    emiException.getMessage());

                        } catch (Exception updateException) {

                            updateException.printStackTrace();
                        }
                    }
                }
            }

        } catch (Exception e) {

            System.err.println(
                    "Fatal error in EmiExecutionScheduler: "
                    + e.getMessage());

            e.printStackTrace();
        }
    }


    /**
     * Successful execution update.
     */
    private void updateExecutionSuccess(
            Connection conn,
            long trackingId,
            String executionId,
            String cfExecutionId,
            String executionStatus,
            String paymentStatus,
            String response)
            throws SQLException {

        String sql =
                "UPDATE cashfree_emi_tracking " +
                "SET execution_id = ?, " +
                "cf_execution_id = ?, " +
                "execution_status = ?, " +
                "payment_status = ?, " +
                "execution_response = ?, " +
                "status = 'EXECUTION_INITIATED', " +
                "last_action = 'EXECUTE', " +
                "execution_at = NOW() " +
                "WHERE id = ?";

        try (PreparedStatement ps =
                     conn.prepareStatement(sql)) {

            ps.setString(1, executionId);
            ps.setString(2, cfExecutionId);
            ps.setString(3, executionStatus);
            ps.setString(4, paymentStatus);
            ps.setString(5, response);
            ps.setLong(6, trackingId);

            ps.executeUpdate();
        }
    }


    /**
     * Store execution response when response is received
     * but execution failed.
     */
    private void updateExecutionResponse(
            Connection conn,
            long trackingId,
            String executionId,
            String cfExecutionId,
            String status,
            String response)
            throws SQLException {

        String sql =
                "UPDATE cashfree_emi_tracking " +
                "SET execution_id = ?, " +
                "cf_execution_id = ?, " +
                "execution_response = ?, " +
                "status = ?, " +
                "last_action = 'EXECUTE', " +
                "last_error = 'Cashfree execution failed' " +
                "WHERE id = ?";

        try (PreparedStatement ps =
                     conn.prepareStatement(sql)) {

            ps.setString(1, executionId);
            ps.setString(2, cfExecutionId);
            ps.setString(3, response);
            ps.setString(4, status);
            ps.setLong(5, trackingId);

            ps.executeUpdate();
        }
    }


    /**
     * Store execution exception/failure.
     */
    private void updateExecutionFailure(
            Connection conn,
            long trackingId,
            String status,
            String error)
            throws SQLException {

        String sql =
                "UPDATE cashfree_emi_tracking " +
                "SET status = ?, " +
                "last_action = 'EXECUTE', " +
                "last_error = ?, " +
                "retry_count = retry_count + 1 " +
                "WHERE id = ?";

        try (PreparedStatement ps =
                     conn.prepareStatement(sql)) {

            ps.setString(1, status);
            ps.setString(2, error);
            ps.setLong(3, trackingId);

            ps.executeUpdate();
        }
    }
}