-- =============================================================================
-- MIGRATION: Rename plan tiers starter/growth/enterprise → free/basic/premium
-- Aligns Organization.plan with the real Shopora pricing page vocabulary
-- (Free/Basic/Premium) instead of the placeholder starter/growth/enterprise
-- names that predated it. Mapping preserves the old approval-tier intent:
-- starter was the reviewed tier, growth/enterprise were auto-approved —
-- so starter→free, growth→basic, enterprise→premium.
-- Run: idempotent — safe to re-execute
-- =============================================================================

BEGIN;

-- Drop whatever the auto-generated CHECK constraint on `plan` is actually
-- named (migration 001 added it inline, unnamed — don't assume a name).
DO $$
DECLARE
  v_conname text;
BEGIN
  SELECT conname INTO v_conname
  FROM pg_constraint
  WHERE conrelid = 'platform.organizations'::regclass
    AND contype = 'c'
    AND pg_get_constraintdef(oid) ILIKE '%plan%IN%';
  IF v_conname IS NOT NULL THEN
    EXECUTE format('ALTER TABLE platform.organizations DROP CONSTRAINT %I', v_conname);
  END IF;
END $$;

-- One-time remap — safe to re-run: a row already on the new vocabulary
-- simply won't match any WHERE clause below.
UPDATE platform.organizations SET plan = 'free',    "updatedOn" = NOW() WHERE plan = 'starter';
UPDATE platform.organizations SET plan = 'basic',   "updatedOn" = NOW() WHERE plan = 'growth';
UPDATE platform.organizations SET plan = 'premium', "updatedOn" = NOW() WHERE plan = 'enterprise';

ALTER TABLE platform.organizations ALTER COLUMN plan SET DEFAULT 'free';

DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM pg_constraint WHERE conname = 'organizations_plan_check'
  ) THEN
    ALTER TABLE platform.organizations
      ADD CONSTRAINT "organizations_plan_check"
      CHECK (plan IN ('free', 'basic', 'premium'));
  END IF;
END $$;

COMMIT;

-- Verify
SELECT plan, COUNT(*) FROM platform.organizations GROUP BY plan ORDER BY plan;
