# Copyright (c) 2024, JINGROW
# For license information, please see license.txt

import jingrow


def execute():
	logs = jingrow.get_all(
		"Stripe Webhook Log",
		{"event_type": "payment_intent.payment_failed"},
		["name", "payload", "customer_id"],
	)

	for log in logs:
		payload = jingrow.parse_json(log.payload)
		if payment_method_id := (
			payload.get("data", {})
			.get("object", {})
			.get("last_payment_error", {})
			.get("payment_method", {})
			.get("id")
		):
			stripe_payment_method = jingrow.db.get_value(
				"Stripe Payment Method",
				{
					"stripe_customer_id": log.customer_id,
					"stripe_payment_method_id": payment_method_id,
				},
				"name",
			)
			jingrow.db.set_value(
				"Stripe Webhook Log",
				log.name,
				"stripe_payment_method",
				stripe_payment_method,
				update_modified=False,
			)
