import { eq } from "drizzle-orm";
import { subscriptions } from "@zmeel/db";
import { getManagedApiKey } from "./managed-api-keys.js";
/**
 * Retrieve the subscription for a given company.
 */
export async function getSubscription(db, companyId) {
    const rows = await db
        .select()
        .from(subscriptions)
        .where(eq(subscriptions.companyId, companyId))
        .limit(1);
    return rows[0] ?? null;
}
/**
 * Create a free-tier subscription for a newly provisioned company.
 */
export async function createFreeSubscription(db, companyId) {
    const now = new Date();
    const rows = await db
        .insert(subscriptions)
        .values({
        companyId,
        plan: "free",
        status: "active",
        monthlyBudgetCents: 500, // $5 free tier
        apiKeyMode: "managed",
        createdAt: now,
        updatedAt: now,
    })
        .returning();
    return rows[0];
}
/**
 * Returns the API key a company should use for Anthropic calls.
 * If BYOK mode and key is set, returns the BYOK key.
 * Otherwise returns the platform managed key.
 */
export async function getApiKeyForCompany(db, companyId, provider = "anthropic") {
    const sub = await getSubscription(db, companyId);
    if (sub && sub.apiKeyMode === "byok" && sub.anthropicApiKey) {
        return sub.anthropicApiKey;
    }
    return getManagedApiKey(provider);
}
/**
 * Switch between managed and BYOK API key modes.
 */
export async function updateApiKeyMode(db, companyId, mode, apiKey) {
    const now = new Date();
    const rows = await db
        .update(subscriptions)
        .set({
        apiKeyMode: mode,
        anthropicApiKey: mode === "byok" ? (apiKey ?? null) : null,
        updatedAt: now,
    })
        .where(eq(subscriptions.companyId, companyId))
        .returning();
    return rows[0] ?? null;
}
//# sourceMappingURL=billing.js.map