// Script to create missing Helcim payment plans
// Run with: node scripts/setup-helcim-plans.js

import { config } from "dotenv";
import { fileURLToPath } from "url";
import { dirname, resolve } from "path";

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

// Load .env file
config({ path: resolve(__dirname, "../.env") });

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

async function createPlan(name, amount) {
  const helcimToken = process.env.NUXT_PUBLIC_HELCIM_TOKEN;

  if (!helcimToken) {
    throw new Error(
      "NUXT_PUBLIC_HELCIM_TOKEN environment variable not set in .env file",
    );
  }

  console.log(`Creating plan: ${name} ($${amount}/month)...`);

  const response = await fetch(`${HELCIM_API_BASE}/payment-plans`, {
    method: "POST",
    headers: {
      accept: "application/json",
      "content-type": "application/json",
      "api-token": helcimToken,
    },
    body: JSON.stringify({
      name: name,
      description: `Ghost Guild ${name}`,
      type: "subscription",
      status: "active",
      currency: "CAD",
      setupAmount: 0,
      recurringAmount: parseFloat(amount),
      billingPeriod: "monthly",
      billingPeriodIncrements: 1,
      dateBilling: "Sign-up",
      termType: "forever",
      freeTrialPeriod: 0,
      taxType: "customer",
      paymentMethod: "card",
    }),
  });

  if (!response.ok) {
    const errorText = await response.text();
    throw new Error(`Failed to create plan: ${errorText}`);
  }

  const planData = await response.json();
  console.log(`✓ Created plan ID: ${planData.id}`);

  return planData;
}

async function main() {
  console.log("Setting up Helcim payment plans...\n");

  const plans = [
    { name: "Ghost Guild - Member ($15)", amount: 15, tier: "MEMBER" },
    { name: "Ghost Guild - Advocate ($30)", amount: 30, tier: "ADVOCATE" },
    { name: "Ghost Guild - Champion ($50)", amount: 50, tier: "CHAMPION" },
  ];

  const results = [];

  for (const plan of plans) {
    try {
      const result = await createPlan(plan.name, plan.amount);
      results.push({
        tier: plan.tier,
        planId: result.id,
        amount: plan.amount,
      });
    } catch (error) {
      console.error(`✗ Failed to create ${plan.name}:`, error.message);
    }
  }

  console.log("\n--- Plan IDs to update in contributions.js ---");
  results.forEach(({ tier, planId, amount }) => {
    console.log(`${tier}: helcimPlanId: ${planId}, // $${amount}/month`);
  });

  console.log("\n--- Copy this to update server/config/contributions.js ---");
  console.log(`
  MEMBER: {
    value: '15',
    amount: 15,
    label: '$15 - I can sustain the community',
    tier: 'member',
    helcimPlanId: ${results.find((r) => r.tier === "MEMBER")?.planId || "null"},
    ...
  },
  ADVOCATE: {
    value: '30',
    amount: 30,
    label: '$30 - I can support others too',
    tier: 'advocate',
    helcimPlanId: ${results.find((r) => r.tier === "ADVOCATE")?.planId || "null"},
    ...
  },
  CHAMPION: {
    value: '50',
    amount: 50,
    label: '$50 - I want to sponsor multiple members',
    tier: 'champion',
    helcimPlanId: ${results.find((r) => r.tier === "CHAMPION")?.planId || "null"},
    ...
  }
  `);
}

main().catch(console.error);
