import { Hono } from "hono";
import { apiError } from "../lib/errors";
import type { AppEnv } from "../types";

export const usage = new Hono<AppEnv>();

usage.get("/", async (c) => {
  const site = c.get("site");
  const license = await c.env.DB.prepare(
    "SELECT storage_bytes_limit, retention_days FROM licenses WHERE license_key = ?",
  )
    .bind(site.license_key)
    .first<{ storage_bytes_limit: number; retention_days: number }>();
  if (!license) return apiError(c, 403, "invalid_license", "License not found");

  const count = await c.env.DB.prepare(
    "SELECT COUNT(*) AS n FROM snapshots WHERE site_id = ? AND status = 'complete'",
  )
    .bind(site.id)
    .first<{ n: number }>();

  return c.json({
    storage_bytes_used: site.storage_bytes_used,
    storage_bytes_limit: license.storage_bytes_limit,
    snapshot_count: count?.n ?? 0,
    retention_days: license.retention_days,
  });
});
