// packages/functions/src/firebase/billing/createCustomerPortal.ts

/**
 * @fileoverview Create Customer Portal Function
 * @description Generates Stripe Customer Portal URL for payment method management
 *
 * @version 0.0.1
 * @since 0.0.1
 * @author AMBROISE PARK Consulting
 */

import { getFirebaseAdminAuth } from '@donotdev/firebase/server';
import * as v from 'valibot';

import { handleError } from '../../shared/errorHandling.js';
import { stripe, validateStripeEnvironment } from '../../shared/utils.js';
import { createBaseFunction } from '../baseFunction.js';
import { STRIPE_CONFIG } from '../config/constants.js';

import type { CallableRequest } from 'firebase-functions/v2/https';

const customerPortalSchema = v.object({
  userId: v.string(),
  returnUrl: v.optional(v.pipe(v.string(), v.url())),
});

async function createCustomerPortalLogic(
  data: { userId: string; returnUrl?: string },
  context: { uid: string; request: CallableRequest }
) {
  validateStripeEnvironment();

  const { userId, returnUrl } = data;

  // Get customer ID from user claims
  const user = await getFirebaseAdminAuth().getUser(userId);
  const currentClaims = user.customClaims || {};
  const customerId = currentClaims.subscription?.customerId;

  if (!customerId) {
    throw handleError(new Error('No customer found'));
  }

  // Create portal session
  const session = await stripe.billingPortal.sessions.create({
    customer: customerId,
    return_url: returnUrl || `${process.env.FRONTEND_URL}/billing`,
  });

  return {
    url: session.url,
  };
}

export function createCustomerPortal() {
  return createBaseFunction(
    STRIPE_CONFIG,
    customerPortalSchema,
    'create_customer_portal',
    createCustomerPortalLogic
  );
}
