import { Router } from "express";
import { assertCompanyAccess, assertBoard } from "./authz.js";
import { getSubscription, updateApiKeyMode } from "../services/billing.js";
export function billingRoutes(db) {
    const router = Router();
    /**
     * GET /api/companies/:companyId/billing
     * Returns subscription / billing info for the company.
     */
    router.get("/companies/:companyId/billing", async (req, res) => {
        const companyId = req.params.companyId;
        assertCompanyAccess(req, companyId);
        const sub = await getSubscription(db, companyId);
        if (!sub) {
            res.status(404).json({ error: "No subscription found for this company" });
            return;
        }
        // Never leak the raw BYOK key — just indicate whether one is set
        res.json({
            id: sub.id,
            companyId: sub.companyId,
            stripeCustomerId: sub.stripeCustomerId,
            stripeSubscriptionId: sub.stripeSubscriptionId,
            plan: sub.plan,
            status: sub.status,
            currentPeriodStart: sub.currentPeriodStart,
            currentPeriodEnd: sub.currentPeriodEnd,
            monthlyBudgetCents: sub.monthlyBudgetCents,
            apiKeyMode: sub.apiKeyMode,
            hasAnthropicApiKey: !!sub.anthropicApiKey,
            createdAt: sub.createdAt,
            updatedAt: sub.updatedAt,
        });
    });
    /**
     * POST /api/companies/:companyId/billing/api-key-mode
     * Body: { mode: "managed" | "byok", apiKey?: string }
     */
    router.post("/companies/:companyId/billing/api-key-mode", async (req, res) => {
        const companyId = req.params.companyId;
        assertCompanyAccess(req, companyId);
        assertBoard(req);
        const { mode, apiKey } = req.body;
        if (mode !== "managed" && mode !== "byok") {
            res.status(400).json({ error: "mode must be 'managed' or 'byok'" });
            return;
        }
        if (mode === "byok" && (!apiKey || typeof apiKey !== "string" || !apiKey.trim())) {
            res.status(400).json({ error: "apiKey is required when switching to BYOK mode" });
            return;
        }
        const updated = await updateApiKeyMode(db, companyId, mode, apiKey?.trim());
        if (!updated) {
            res.status(404).json({ error: "No subscription found for this company" });
            return;
        }
        res.json({
            id: updated.id,
            companyId: updated.companyId,
            plan: updated.plan,
            status: updated.status,
            apiKeyMode: updated.apiKeyMode,
            hasAnthropicApiKey: !!updated.anthropicApiKey,
            updatedAt: updated.updatedAt,
        });
    });
    return router;
}
//# sourceMappingURL=billing.js.map