/**
 * Billing History API
 *
 * GREEN PHASE: Full implementation routed through billing adapter.
 * Append-only audit log for all billing events.
 * Uses the billing adapter for Prisma/Convex routing.
 */

import { billingHistory } from "@/lib/adapters/billing";

export interface CreateBillingEventInput {
  customerId: string;
  subscriptionId?: string | null;
  invoiceId?: string | null;
  paymentIntentId?: string | null;
  event: string;
  amount: number;
  currency: string;
  metadata?: Record<string, any>;
}

export interface DateRangeQuery {
  customerId: string;
  startDate: Date;
  endDate: Date;
}

/**
 * Create a billing history event (append-only)
 */
export async function createBillingEvent(data: CreateBillingEventInput) {
  return await billingHistory.create({
    data: {
      customerId: data.customerId,
      subscriptionId: data.subscriptionId || null,
      invoiceId: data.invoiceId || null,
      paymentIntentId: data.paymentIntentId || null,
      event: data.event,
      amount: data.amount,
      currency: data.currency,
      metadata: data.metadata || {},
    },
  });
}

/**
 * Get all billing history for a customer
 */
export async function getBillingHistoryByCustomer(customerId: string) {
  return await billingHistory.findMany({
    where: { customerId },
    orderBy: { createdAt: "desc" },
  });
}

/**
 * Get billing history for a specific subscription
 */
export async function getBillingHistoryBySubscription(subscriptionId: string) {
  return await billingHistory.findMany({
    where: { subscriptionId },
    orderBy: { createdAt: "desc" },
  });
}

/**
 * Get billing history by event type
 */
export async function getBillingHistoryByEventType(eventType: string) {
  return await billingHistory.findMany({
    where: { event: eventType },
    orderBy: { createdAt: "desc" },
  });
}

/**
 * Get billing history by date range
 */
export async function getBillingHistoryByDateRange(query: DateRangeQuery) {
  return await billingHistory.findMany({
    where: {
      customerId: query.customerId,
      createdAt: {
        gte: query.startDate,
        lte: query.endDate,
      },
    },
    orderBy: { createdAt: "desc" },
  });
}

/**
 * Validate append-only pattern (no updatedAt field)
 */
export async function validateAppendOnlyPattern(id: string): Promise<boolean> {
  const record = await billingHistory.findUnique({
    where: { id },
  });

  if (!record) {
    return false;
  }

  // Check that record has createdAt but no updatedAt
  // In Prisma, if updatedAt doesn't exist in schema, this will always be true
  return "createdAt" in record && !("updatedAt" in record);
}
