-- Migration 023: Add billing and usage metering tables
-- Phase 4, WS6 — Billing & Usage Metering

-- ── Tenant subscriptions ────────────────────────────────────────────────────────
-- Tracks the Stripe subscription status for each tenant/organization.
-- One row per tenant. When no row exists, the tenant is on the free tier.
CREATE TABLE IF NOT EXISTS tenant_subscriptions (
  id                      UUID        PRIMARY KEY DEFAULT gen_random_uuid(),
  tenant_id               UUID        NOT NULL REFERENCES organizations(org_id) ON DELETE CASCADE,
  status                  VARCHAR(32) NOT NULL DEFAULT 'free',
  stripe_customer_id      VARCHAR(255),
  stripe_subscription_id  VARCHAR(255),
  current_period_end      TIMESTAMPTZ,
  created_at              TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at              TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- One subscription row per tenant (UPSERT target)
ALTER TABLE tenant_subscriptions
  ADD CONSTRAINT uq_tenant_subscriptions_tenant_id UNIQUE (tenant_id);

CREATE INDEX IF NOT EXISTS idx_tenant_subscriptions_tenant_id
  ON tenant_subscriptions(tenant_id);

-- ── Usage events ─────────────────────────────────────────────────────────────────
-- Daily usage counters per tenant and metric type.
-- Uses UPSERT with ON CONFLICT to accumulate counts without duplicates.
CREATE TABLE IF NOT EXISTS usage_events (
  id          UUID        PRIMARY KEY DEFAULT gen_random_uuid(),
  tenant_id   UUID        NOT NULL,
  date        DATE        NOT NULL DEFAULT CURRENT_DATE,
  metric_type VARCHAR(64) NOT NULL,
  count       INTEGER     NOT NULL DEFAULT 0,
  created_at  TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Unique constraint enables UPSERT: ON CONFLICT (tenant_id, date, metric_type)
ALTER TABLE usage_events
  ADD CONSTRAINT uq_usage_events_tenant_date_metric
  UNIQUE (tenant_id, date, metric_type);

CREATE INDEX IF NOT EXISTS idx_usage_events_tenant_date
  ON usage_events(tenant_id, date);
