// Cancel member subscription
import Member from "../../models/member.js";
import { cancelHelcimSubscription } from "../../utils/helcim.js";

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

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

    try {
      await cancelHelcimSubscription(member.helcimSubscriptionId);
    } catch (cancelError) {
      console.error("Error canceling Helcim subscription:", cancelError);
      // 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',
          contributionAmount: 0,
          helcimSubscriptionId: null,
          paymentMethod: 'none',
          subscriptionEndDate: new Date(),
        },
        $unset: { nextBillingDate: 1 },
      },
      { runValidators: false }
    );

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

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