// Cancel member subscription
import Member from "../../models/member.js";

const HELCIM_API_BASE = "https://api.helcim.com/v2";

export default defineEventHandler(async (event) => {
  try {
    const member = await requireAuth(event);
    const config = useRuntimeConfig(event);

    // If already on free tier, nothing to cancel
    if (member.contributionTier === "0" || !member.helcimSubscriptionId) {
      return {
        success: true,
        message: "No active subscription to cancel",
        status: member.status,
        contributionTier: member.contributionTier,
      };
    }

    const helcimToken = config.helcimApiToken;

    try {
      // Cancel Helcim subscription
      const response = await fetch(
        `${HELCIM_API_BASE}/subscriptions/${member.helcimSubscriptionId}`,
        {
          method: "DELETE",
          headers: {
            accept: "application/json",
            "api-token": helcimToken,
          },
        },
      );

      if (!response.ok) {
        const errorText = await response.text();
        console.error(
          "Failed to cancel Helcim subscription:",
          response.status,
          errorText,
        );
        // Continue anyway - we'll update the member record
      }
    } catch (error) {
      console.error("Error canceling Helcim subscription:", error);
      // Continue anyway - we'll update the member record
    }

    // Update member status — pending_payment (not cancelled) so member can re-subscribe
    await Member.findByIdAndUpdate(
      member._id,
      {
        $set: {
          status: 'pending_payment',
          contributionTier: '0',
          helcimSubscriptionId: null,
          paymentMethod: 'none',
          subscriptionEndDate: new Date(),
        },
      },
      { runValidators: false }
    );

    logActivity(member._id, 'subscription_cancelled', {
      effectiveDate: new Date().toISOString()
    })

    return {
      success: true,
      message: "Subscription cancelled successfully",
      status: 'pending_payment',
      contributionTier: '0',
    };
  } catch (error) {
    console.error("Error cancelling subscription:", error);
    throw createError({
      statusCode: error.statusCode || 500,
      statusMessage: error.message || "Failed to cancel subscription",
    });
  }
});
