import { convexMutation, convexQuery } from "@/lib/convex-client";

interface SyncStripeSubscriptionParams {
  prismaSubscriptionId?: string;
  userId: string;
  stripeCustomerId: string;
  stripeSubscriptionId: string;
  stripePriceId: string;
  tierId: string;
  status: string;
  billingPeriod: "monthly" | "yearly";
  currentPeriodEnd: Date;
  trialEndsAt?: Date | null;
  paymentMethodId?: string | null;
  cardBrand?: string | null;
  cardLastFour?: string | null;
  setupFeePaid?: boolean;
  setupFeeAmount?: number | null;
  setupFeePaidAt?: Date | null;
  lastPaymentDate?: Date | null;
  preferredCurrency?: string | null;
}

export async function syncStripeSubscriptionToConvex(
  params: SyncStripeSubscriptionParams,
): Promise<void> {
  const currentPeriodEnd = params.currentPeriodEnd.getTime();
  const trialEndsAt = params.trialEndsAt?.getTime();
  const setupFeePaidAt = params.setupFeePaidAt?.getTime();
  const lastPaymentDate = params.lastPaymentDate?.getTime();

  // Try to find existing subscription by Stripe ID first, then by userId
  let existingSubscription = await convexQuery<Record<string, unknown>>(
    "billing/queries:getByStripeSubscriptionId",
    { stripeSubscriptionId: params.stripeSubscriptionId },
  ).catch(() => null);

  // If not found by stripe ID, look for any subscription for this user (e.g. old trial)
  if (!existingSubscription?._id) {
    existingSubscription = await convexQuery<Record<string, unknown>>(
      "billing/queries:getActiveSubscription",
      { userId: params.userId },
    ).catch(() => null);
  }

  // Still not found? Try getting ANY subscription for user (even expired)
  if (!existingSubscription?._id) {
    existingSubscription = await convexQuery<Record<string, unknown>>(
      "billing/queries:getSubscription",
      { userId: params.userId },
    ).catch(() => null);
  }

  if (existingSubscription?._id) {
    // Update existing subscription with new Stripe data
    await convexMutation("billing/mutations:updateSubscription", {
      id: existingSubscription._id,
      status: params.status,
      tierId: params.tierId,
      stripePriceId: params.stripePriceId,
      billingPeriod: params.billingPeriod,
      currentPeriodEnd,
      trialEndsAt,
      paymentMethodId: params.paymentMethodId ?? undefined,
      cardBrand: params.cardBrand ?? undefined,
      cardLastFour: params.cardLastFour ?? undefined,
      setupFeePaid: params.setupFeePaid ?? false,
      setupFeeAmount: params.setupFeeAmount ?? undefined,
      setupFeePaidAt,
      lastPaymentDate,
    });
  } else {
    // No subscription at all — create new
    await convexMutation("billing/mutations:createSubscription", {
      prismaId: params.prismaSubscriptionId,
      userId: params.userId,
      stripeCustomerId: params.stripeCustomerId,
      stripeSubscriptionId: params.stripeSubscriptionId,
      stripePriceId: params.stripePriceId,
      tierId: params.tierId,
      status: params.status,
      billingPeriod: params.billingPeriod,
      currentPeriodEnd,
      trialEndsAt,
      paymentMethodId: params.paymentMethodId ?? undefined,
      cardBrand: params.cardBrand ?? undefined,
      cardLastFour: params.cardLastFour ?? undefined,
      setupFeePaid: params.setupFeePaid ?? false,
      setupFeeAmount: params.setupFeeAmount ?? undefined,
      setupFeePaidAt,
      lastPaymentDate,
    });
  }

  await convexMutation("auth/mutations:updateUserNoAuth", {
    userId: params.userId,
    stripeCustomerId: params.stripeCustomerId,
    selectedPackage: params.tierId || undefined,
    preferredCurrency: params.preferredCurrency ?? undefined,
    selectedBillingPeriod: params.billingPeriod,
  });
}
