ALTER TABLE "organization" ADD COLUMN "mcp_monthly_usage" integer DEFAULT 0 NOT NULL;--> statement-breakpoint
ALTER TABLE "organization" ADD COLUMN "mcp_usage_month" text;--> statement-breakpoint
-- Backfill (QW2-B): the new counter starts at the default (0, no month) for
-- every org, which would silently reset in-flight quota usage to 0 on deploy
-- — an org mid-way through its monthly allotment would get a fresh budget for
-- free until the SUM-based path is fully retired. Seed it from the current
-- source of truth (SUM(mcp_api_keys.monthly_count) for the CURRENT UTC month,
-- same "YYYY-MM" convention as currentMonth() in src/lib/mcp/quota.ts) so the
-- switchover is usage-neutral. Orgs with no current-month key usage keep the
-- column defaults (0 / NULL), which the read/enforcement path already treats
-- as "no usage yet" (NULL month != current month -> effective usage 0).
UPDATE "organization" AS o
SET
  "mcp_monthly_usage" = sub.usage,
  "mcp_usage_month" = to_char(now() AT TIME ZONE 'utc', 'YYYY-MM')
FROM (
  SELECT "org_id", sum("monthly_count")::int AS usage
  FROM "mcp_api_keys"
  WHERE "request_month" = to_char(now() AT TIME ZONE 'utc', 'YYYY-MM')
  GROUP BY "org_id"
) AS sub
WHERE o.id = sub.org_id;