import { createAdminClient } from '@/shared/db/supabase-client';
import { stripe } from '@/shared/billing/stripe-client';

// --- ASA GENERATED START ---
// Reconciliation job template — identifies and repairs drift between Stripe and local DB.
// Run periodically (e.g., daily via cron) to catch missed webhooks or state inconsistencies.
// --- ASA GENERATED END ---

// --- USER CODE START ---

export interface ReconciliationResult {
  checked: number;
  drifted: number;
  repaired: number;
  errors: string[];
}

/**
 * Reconcile local subscription state with Stripe.
 * Fetches all active Stripe subscriptions and compares with local DB.
 * Repairs any drift found.
 */
export async function reconcileSubscriptions(): Promise<ReconciliationResult> {
  const supabase = createAdminClient();
  const result: ReconciliationResult = { checked: 0, drifted: 0, repaired: 0, errors: [] };

  try {
    // Get all local subscriptions with Stripe customer IDs
    const { data: localSubs } = await supabase
      .from('subscriptions')
      .select('user_id, stripe_customer_id, stripe_subscription_id, plan, status')
      .not('stripe_customer_id', 'is', null);

    if (!localSubs) return result;

    for (const local of localSubs) {
      result.checked++;

      try {
        if (!local.stripe_subscription_id) continue;

        // Fetch current state from Stripe (source of truth)
        const stripeSub = await stripe.subscriptions.retrieve(local.stripe_subscription_id);

        // Compare status
        const stripeStatus = mapStripeStatus(stripeSub.status);
        if (local.status !== stripeStatus) {
          result.drifted++;

          await supabase
            .from('subscriptions')
            .update({ status: stripeStatus })
            .eq('user_id', local.user_id);

          result.repaired++;
          console.log(
            `[reconciliation] Repaired drift for user ${local.user_id}: ` +
            `${local.status} → ${stripeStatus}`,
          );
        }
      } catch (err) {
        result.errors.push(
          `User ${local.user_id}: ${err instanceof Error ? err.message : String(err)}`,
        );
      }
    }
  } catch (err) {
    result.errors.push(`Fatal: ${err instanceof Error ? err.message : String(err)}`);
  }

  return result;
}

function mapStripeStatus(stripeStatus: string): string {
  switch (stripeStatus) {
    case 'active': return 'active';
    case 'trialing': return 'trialing';
    case 'past_due': return 'past_due';
    case 'canceled': return 'canceled';
    case 'unpaid': return 'past_due';
    default: return stripeStatus;
  }
}

// --- USER CODE END ---
