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

/**
 * @fileoverview Billing Health Check
 * @description Comprehensive health check for billing system
 *
 * @version 0.0.1
 * @since 0.0.1
 * @author AMBROISE PARK Consulting
 */

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

import { isFirestoreConfigured } from '../../shared/utils/detectFirestore.js';
import { stripe } from '../../shared/utils.js';
import { STRIPE_CONFIG } from '../config/constants.js';

/**
 * Comprehensive health check for billing system
 * GET /billingHealth
 */
export const billingHealth = onRequest(STRIPE_CONFIG, async (req, res) => {
  const checks: Record<string, string> = {};
  let overallStatus: 'healthy' | 'degraded' | 'unhealthy' = 'healthy';

  // Check Stripe connection
  try {
    await stripe.products.list({ limit: 1 });
    checks.stripe = 'connected';
  } catch (error) {
    checks.stripe = 'error';
    overallStatus = 'unhealthy';
  }

  // Check idempotency storage
  checks.idempotency = isFirestoreConfigured() ? 'firestore' : 'in-memory';
  if (checks.idempotency === 'in-memory') {
    overallStatus = overallStatus === 'healthy' ? 'degraded' : overallStatus;
  }

  // Check environment variables
  const requiredEnvVars = [
    'STRIPE_SECRET_KEY',
    'STRIPE_WEBHOOK_SECRET',
    'STRIPE_API_VERSION',
  ];
  const missingEnvVars = requiredEnvVars.filter((v) => !process.env[v]);
  checks.environment = missingEnvVars.length === 0 ? 'configured' : 'missing';
  if (missingEnvVars.length > 0) {
    checks.missingEnvVars = missingEnvVars.join(', ');
    overallStatus = 'unhealthy';
  }

  const health = {
    status: overallStatus,
    timestamp: Date.now(),
    checks,
    version: process.env.STRIPE_API_VERSION || 'unknown',
  };

  const statusCode =
    overallStatus === 'healthy'
      ? 200
      : overallStatus === 'degraded'
        ? 200
        : 503;
  res.status(statusCode).json(health);
});
