"use server"
import {
  createCheckoutSession,
  cancelSubscription as cancelStripeSubscription,
  getSubscription as getSubscriptionFromCommon,
  reactivateSubscription as reactivateSubscriptionFromCommon,
} from "@codeflash-ai/common"
import * as Sentry from "@sentry/nextjs"

export async function upgradeSubscription(
  userId: string,
  period: "monthly" | "yearly" = "monthly",
) {
  try {
    // Select price ID based on period
    const priceId =
      period === "yearly"
        ? process.env.STRIPE_PRO_PRICE_YEARLY_ID
        : process.env.STRIPE_PRO_PRICE_MONTHLY_ID

    // Ensure priceId is defined
    if (!priceId) {
      throw new Error(`Stripe price ID is not defined for ${period} billing period.`)
    }
    // Use the common function to create checkout
    const checkoutUrl = await createCheckoutSession(userId, priceId, {
      period,
      successUrl: `${process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3000"}/app/billing?success=true`,
      cancelUrl: `${process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3000"}/app/billing?canceled=true`,
    })

    return checkoutUrl
  } catch (error) {
    Sentry.captureException(error)
    console.error("Error creating checkout:", error)
    throw error
  }
}

export async function cancelSubscription(userId: string) {
  try {
    // Use the common function to cancel subscription
    await cancelStripeSubscription(userId)
  } catch (error) {
    console.error("Error canceling subscription:", error)
    Sentry.captureException(error)
    throw error
  }
}

export async function getSubscription(userId: string) {
  return getSubscriptionFromCommon(userId)
}

export async function reactivateSubscription(userId: string) {
  try {
    await reactivateSubscriptionFromCommon(userId)
    return { success: true }
  } catch (error: any) {
    console.error("Error reactivating subscription:", error)
    Sentry.captureException(error)
    return { success: false, error: error.message }
  }
}
