// Stripe SDK + plan definitions + customer lookup helper.

import Stripe from 'stripe';
import { getServiceSupabase } from './db';

let _stripe: Stripe | null = null;

export function getStripe(): Stripe {
  if (_stripe) return _stripe;
  const key = process.env.STRIPE_SECRET_KEY;
  if (!key) throw new Error('STRIPE_SECRET_KEY must be set');
  // Stripe SDK 17+ requires apiVersion '2025-02-24.acacia'.
  // Bump when stripe SDK ships a new latest version.
  _stripe = new Stripe(key, { apiVersion: '2025-02-24.acacia' });
  return _stripe;
}

export interface Plan {
  id: string;
  name: string;
  priceMonthly: number;
  stripePriceId?: string;
  features: string[];
}

/**
 * Stub plan definitions. Replace `stripePriceId` with your live Price ids
 * once you've created them in https://dashboard.stripe.com → Products.
 */
export function listPlans(): Plan[] {
  return [
    {
      id: 'starter',
      name: 'Starter',
      priceMonthly: 0,
      features: ['1 project', 'Community support'],
    },
    {
      id: 'pro',
      name: 'Pro',
      priceMonthly: 29,
      stripePriceId: process.env.STRIPE_PRICE_PRO,
      features: ['Unlimited projects', 'Priority support', 'Custom domain'],
    },
    {
      id: 'team',
      name: 'Team',
      priceMonthly: 99,
      stripePriceId: process.env.STRIPE_PRICE_TEAM,
      features: ['Everything in Pro', 'Up to 10 team members', 'SSO'],
    },
  ];
}

/**
 * Find or create a Stripe customer for the given Clerk user id. Persists
 * the mapping in `subscriptions.stripe_customer_id`.
 */
export async function getOrCreateStripeCustomerId(clerkUserId: string): Promise<string> {
  const supabase = getServiceSupabase();
  const { data: existing } = await supabase
    .from('users')
    .select('stripe_customer_id, email')
    .eq('clerk_id', clerkUserId)
    .maybeSingle();
  if (existing?.stripe_customer_id) return existing.stripe_customer_id;

  const customer = await getStripe().customers.create({
    email: existing?.email || undefined,
    metadata: { clerk_user_id: clerkUserId },
  });

  await supabase
    .from('users')
    .update({ stripe_customer_id: customer.id })
    .eq('clerk_id', clerkUserId);

  return customer.id;
}
