-- ============================================================
-- Kreş SaaS — ENUM -> TEXT Normalize (legacy DB düzeltmesi)
-- Amaç:
--   tenants.plan, subscriptions.plan, subscriptions.status
-- alanlarını USER-DEFINED/ENUM tipten TEXT'e taşımak.
-- Bu script idempotenttir; zaten TEXT ise dokunmaz.
-- ============================================================

DO $$
DECLARE
  col_type TEXT;
BEGIN
  SELECT data_type INTO col_type
  FROM information_schema.columns
  WHERE table_schema = 'public'
    AND table_name = 'tenants'
    AND column_name = 'plan';

  IF col_type = 'USER-DEFINED' THEN
    ALTER TABLE public.tenants
      ALTER COLUMN plan TYPE TEXT USING plan::TEXT,
      ALTER COLUMN plan SET DEFAULT 'TRIAL';
  END IF;
END $$;

DO $$
DECLARE
  col_type TEXT;
BEGIN
  SELECT data_type INTO col_type
  FROM information_schema.columns
  WHERE table_schema = 'public'
    AND table_name = 'subscriptions'
    AND column_name = 'plan';

  IF col_type = 'USER-DEFINED' THEN
    ALTER TABLE public.subscriptions
      ALTER COLUMN plan TYPE TEXT USING plan::TEXT,
      ALTER COLUMN plan SET DEFAULT 'TRIAL';
  END IF;
END $$;

DO $$
DECLARE
  col_type TEXT;
BEGIN
  SELECT data_type INTO col_type
  FROM information_schema.columns
  WHERE table_schema = 'public'
    AND table_name = 'subscriptions'
    AND column_name = 'status';

  IF col_type = 'USER-DEFINED' THEN
    ALTER TABLE public.subscriptions
      ALTER COLUMN status TYPE TEXT USING status::TEXT,
      ALTER COLUMN status SET DEFAULT 'TRIAL';
  END IF;
END $$;

