import axios from "axios";
import PlanSubscriptionsList from "../../Models/PlanSubscriptions/PlanSubscriptons";
import { MP_SUBS_STATUS } from "../../Models/PlanSubscriptions/PlanSubscriptions.Adapter.Mongoose";
import { connect } from "mongoose";

export class MercadoPagoWebhookService {
    public async handleWebhook(body: any): Promise<void> {
        await connect(`${process.env.DATABASE_CONNECTION}`);

        // MercadoPago sends 'type' or 'topic' as 'payment'
        const type = body.type || body.topic;
        const dataId = body.data?.id || (body.resource ? body.resource.split("/").pop() : null) || body.id;

        if (type === "payment" && dataId) {
            try {
                // Fetch the payment details from MP API
                const paymentResponse = await axios.get(
                    `https://api.mercadopago.com/v1/payments/${dataId}`,
                    {
                        headers: {
                            Authorization: `Bearer ${process.env.MP_ACCESS_TOKEN}`,
                            "Content-Type": "application/json",
                        },
                    }
                );

                const paymentData = paymentResponse.data;
                const status = paymentData.status; // approved, pending, rejected, etc.
                const userId = paymentData.external_reference; // We passed this when creating preference

                if (userId && status === "approved") {
                    // Update subscription status in DB
                    const subscription = await PlanSubscriptionsList.planSuscriptions.findOne({
                        sessionUser: userId,
                    });

                    if (subscription) {
                        subscription.mpStatus = MP_SUBS_STATUS.AUTHORIZED;
                        subscription.isActive = true;
                        // Assuming endDate is correctly set for the months purchased when preference was created
                        await subscription.save();
                    }
                } else if (userId && status === "rejected") {
                    const subscription = await PlanSubscriptionsList.planSuscriptions.findOne({
                        sessionUser: userId,
                    });

                    if (subscription && subscription.mpStatus !== MP_SUBS_STATUS.AUTHORIZED) {
                        subscription.mpStatus = MP_SUBS_STATUS.CANCELLED;
                        subscription.isActive = false;
                        await subscription.save();
                    }
                }
            } catch (error) {
                console.error("Error handling MercadoPago Webhook:", error);
            }
        }
    }
}
