import Stripe from "stripe"
import * as dotenv from "dotenv"
import { STRIPE_CONFIG } from "../config/stripe.js"
dotenv.config({ path: ".env.local" })
dotenv.config() // fallback

if (!process.env.STRIPE_SECRET_KEY) {
  console.error("⚠️ STRIPE_SECRET_KEY is missing in your .env file")
  process.exit(1)
}

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {
  apiVersion: "2025-08-27.basil",
})

async function setupStripeProducts() {
  try {
    console.log("🚀 Creating Stripe products and prices...\n")

    // Create Pro tier only rn as enterprise moved to custom sales
    const proProduct = await stripe.products.create({
      name: STRIPE_CONFIG.PRICING_TIERS.PRO.name,
      description: `${STRIPE_CONFIG.PRICING_TIERS.PRO.optimizations} optimizations per month`,
      metadata: {
        tier: "pro",
        optimizations: STRIPE_CONFIG.PRICING_TIERS.PRO.optimizations.toString(),
      },
    })
    console.log("✅ Created Pro product:", proProduct.id)

    const proMonthlyPrice = await stripe.prices.create({
      product: proProduct.id,
      unit_amount: STRIPE_CONFIG.PRICING_TIERS.PRO.monthlyPrice,
      currency: "usd",
      recurring: {
        interval: "month",
      },
      metadata: {
        tier: "pro",
        billing_period: "monthly",
        optimizations: STRIPE_CONFIG.PRICING_TIERS.PRO.optimizations.toString(),
      },
    })
    const proYearlyPrice = await stripe.prices.create({
      product: proProduct.id,
      unit_amount: STRIPE_CONFIG.PRICING_TIERS.PRO.yearlyPrice,
      currency: "usd",
      recurring: {
        interval: "month",
      },
      metadata: {
        tier: "pro",
        billing_period: "yearly",
        optimizations: STRIPE_CONFIG.PRICING_TIERS.PRO.optimizations.toString(),
      },
    })
    console.log("✅ Created Pro price:", proYearlyPrice.id)

    const enterpriseProduct = await stripe.products.create({
      name: STRIPE_CONFIG.PRICING_TIERS.ENTERPRISE.name,
      description: "Custom optimizations limit with dedicated support",
      metadata: {
        tier: "enterprise",
        optimizations: "custom",
      },
    })
    console.log("✅ Created Enterprise product:", enterpriseProduct.id)

    console.log("For env variables:")
    console.log(`STRIPE_PRO_PRODUCT_ID=${proProduct.id}`)
    console.log(`STRIPE_PRO_PRICE_MONTHLY_ID=${proMonthlyPrice.id}`)
    console.log(`STRIPE_PRO_PRICE_YEARLY_ID=${proYearlyPrice.id}`)
    console.log(`STRIPE_ENTERPRISE_PRODUCT_ID=${enterpriseProduct.id}`)

    console.log("\nFor cf-webapp")
    console.log(`NEXT_PUBLIC_STRIPE_PRO_PRICE_MONTHLY_ID=${proMonthlyPrice.id}`)
    console.log(`NEXT_PUBLIC_STRIPE_PRO_PRICE_YEARLY_ID=${proYearlyPrice.id}`)
  } catch (error) {
    console.error("❌ Error:", error)
  }
}

console.log("Stripe setup...")
setupStripeProducts()
// We can create it manually from portal as well but easy to edit from the product from script
