/**
 * Subscription Management API
 *
 * GREEN PHASE: Implementation routed through subscriptions adapter.
 * Uses the subscriptions adapter for Prisma/Convex routing.
 */

import { subscriptionsAdapter } from "@/lib/adapters/subscriptions";

export interface CreateSubscriptionInput {
  userId: string;
  stripeCustomerId: string;
  stripeSubscriptionId: string;
  stripePriceId: string;
  tierId: string;
  billingPeriod: "monthly" | "yearly";
  status:
    | "pending_verification"
    | "trialing"
    | "active"
    | "past_due"
    | "canceled"
    | "suspended";
  currentPeriodEnd: Date;
  trialEndsAt?: Date | null;
  cancelAtPeriodEnd?: boolean;
}

export interface UpdateSubscriptionStatusInput {
  status:
    | "pending_verification"
    | "trialing"
    | "active"
    | "past_due"
    | "canceled"
    | "suspended";
  cancelAtPeriodEnd?: boolean;
  cancelledAt?: Date;
  currentPeriodEnd?: Date;
}

export interface UpgradeSubscriptionInput {
  newTierId: string;
  newPriceId: string;
  prorationAmount?: number;
}

/**
 * Create a new subscription in the database
 */
export async function createSubscription(data: CreateSubscriptionInput) {
  return await subscriptionsAdapter.create({
    data: {
      userId: data.userId,
      stripeCustomerId: data.stripeCustomerId,
      stripeSubscriptionId: data.stripeSubscriptionId,
      stripePriceId: data.stripePriceId,
      tierId: data.tierId,
      status: data.status,
      billingPeriod: data.billingPeriod,
      currentPeriodEnd: data.currentPeriodEnd,
      trialEndsAt: data.trialEndsAt,
      cancelAtPeriodEnd: data.cancelAtPeriodEnd,
    },
  });
}

/**
 * Get active subscription for a user
 */
export async function getSubscriptionByUserId(userId: string) {
  return await subscriptionsAdapter.findFirst({
    where: {
      userId,
      status: { not: "incomplete_expired" },
    },
    orderBy: { createdAt: "desc" },
  });
}

/**
 * Get subscription by ID
 */
export async function getSubscriptionById(subscriptionId: string) {
  return await subscriptionsAdapter.findUnique({
    where: { id: subscriptionId },
  });
}

/**
 * Update subscription status
 */
export async function updateSubscriptionStatus(
  subscriptionId: string,
  updates: UpdateSubscriptionStatusInput,
) {
  return await subscriptionsAdapter.update({
    where: { id: subscriptionId },
    data: updates,
  });
}

/**
 * Cancel a subscription (mark for cancellation at period end)
 */
export async function cancelSubscription(subscriptionId: string) {
  return await subscriptionsAdapter.update({
    where: { id: subscriptionId },
    data: {
      cancelAtPeriodEnd: true,
    },
  });
}

/**
 * Upgrade subscription to a higher tier
 */
export async function upgradeSubscription(
  subscriptionId: string,
  upgrade: UpgradeSubscriptionInput,
) {
  return await subscriptionsAdapter.update({
    where: { id: subscriptionId },
    data: {
      tierId: upgrade.newTierId,
      stripePriceId: upgrade.newPriceId,
    },
  });
}
