-- Migration 026: Add tenant tier tracking columns to organizations table
-- Phase 6, WS4 — API Gateway Tiers
--
-- Adds a dedicated `tier` column (ENUM: free/pro/enterprise) and a `tier_updated_at`
-- timestamp column. The existing `plan_tier` VARCHAR column is retained for
-- backward compatibility with the billing/subscription subsystem.

CREATE TYPE IF NOT EXISTS tier_type AS ENUM ('free', 'pro', 'enterprise');

ALTER TABLE organizations
  ADD COLUMN IF NOT EXISTS tier tier_type NOT NULL DEFAULT 'free';

ALTER TABLE organizations
  ADD COLUMN IF NOT EXISTS tier_updated_at TIMESTAMPTZ;

-- Backfill tier from plan_tier for existing rows so the new column is consistent.
UPDATE organizations
  SET tier = plan_tier::tier_type
  WHERE tier = 'free' AND plan_tier IN ('free', 'pro', 'enterprise');

CREATE INDEX IF NOT EXISTS idx_organizations_tier ON organizations(tier);
