import { and, eq } from "drizzle-orm";
import { getDb } from "@/core/db/client";
import { plans, subscriptions } from "@/core/db/schema";

export type TenantSubscriptionSummary = {
  status: string;
  planCode: string;
  planName: string;
  currentPeriodEnd: Date | null;
  cancelAtPeriodEnd: boolean;
};

/**
 * Tenant-scoped subscription summary for dashboard chrome / settings.
 * Never accept tenantId from the client — pass trusted TenantContext.tenantId.
 */
export async function getTenantSubscription(
  tenantId: string,
): Promise<TenantSubscriptionSummary | null> {
  const db = getDb();
  const [row] = await db
    .select({
      status: subscriptions.status,
      currentPeriodEnd: subscriptions.currentPeriodEnd,
      cancelAtPeriodEnd: subscriptions.cancelAtPeriodEnd,
      planCode: plans.code,
      planName: plans.name,
    })
    .from(subscriptions)
    .innerJoin(plans, eq(subscriptions.planId, plans.id))
    .where(and(eq(subscriptions.tenantId, tenantId), eq(plans.isActive, true)))
    .limit(1);

  if (!row) return null;

  return {
    status: row.status,
    planCode: row.planCode,
    planName: row.planName,
    currentPeriodEnd: row.currentPeriodEnd,
    cancelAtPeriodEnd: row.cancelAtPeriodEnd,
  };
}
