#!/usr/bin/python3

import sys

sys.path.insert(0, "/usr/local/mgr5/lib/python")
from billmgr.modules.paymentcgi import PageType, PaymentCgiType, run_cgi
import billmgr.logger as logging
import billmgr.db as db
import billmgr.payment as payment

import paypalexpanded.api as paypal_api

logging.init_logging('ppexpandedrecurringresult')
logger = logging.get_logger('ppexpandedrecurringresult')

PAYMETHOD_MODULE_NAME = "pmpaypalexpanded"

class PayPalRecurringResultCgi(paypal_api.PayPalBaseCgi):
    def cgi_type(self) -> PaymentCgiType:
        return PaymentCgiType.NewRecurring

    def _find_recurring(self, external_id: str) -> int:
        return db.get_first_record_unwrap(
            "SELECT id FROM recurring WHERE paymethod IN (SELECT id FROM paymethod WHERE module = %s) AND data1 = %s",
            PAYMETHOD_MODULE_NAME,
            external_id,
        ).as_int("id")

    def parse_input(self):
        self._recurring_id = self._find_recurring(self.input["order_id"])

    def elid(self) -> str:
        return str(self._recurring_id)

    def process(self):
        paypal_order_id = self.input["order_id"]

        try:
            auth = self.authenticate()
            response = paypal_api.request_capture_order(auth, paypal_order_id)
            captured_order = paypal_api.parse_capture_order(response)

            if captured_order.is_pending:
                external_id = f'{captured_order.order_id}/{captured_order.capture_id}'
                status = payment.RecurringStatus.rsStoring if self.is_stored_paymethod(
                    payment.RecurringStatus(int(self.recurring_params['status']))
                ) else payment.RecurringStatus.rsAdd
                payment.save_recurring_info(int(self.elid()), payment.RecurringInfo(
                    status=status,
                    token='',
                    data1=external_id,
                    data2=self.recurring_params['payment_method'],
                    name=''
                ))
                self.redirect_to_url(self.get_page(PageType.Pending))
            else:
                if not captured_order.stored_token:
                    raise paypal_api.TokenNotFoundError()

                status = payment.RecurringStatus.rsStored if self.is_stored_paymethod(
                    payment.RecurringStatus(int(self.recurring_params['status']))
                ) else payment.RecurringStatus.rsActive

                payment.save_recurring_info(int(self.elid()), payment.RecurringInfo(
                    status=status,
                    token=captured_order.stored_token,
                    data1='',
                    data2=self.recurring_params['payment_method'],
                    name=''
                ))

                paypal_api.request_refund_full_captured_order(auth, captured_order.capture_id)
                self.redirect_to_url(self.get_page(PageType.Success))

        except Exception as e:
            logger.error(f"Recurring setup failed: {e}")
            self.redirect_to_url(self.get_page(PageType.Fail))

if __name__ == "__main__":
    run_cgi(PayPalRecurringResultCgi)
