-- Migration: convert numeric version columns to text to support semantic versions
-- This is idempotent: it only alters columns if they are not already text.

DO $$
BEGIN
  -- Alter version_code to text if needed
  IF EXISTS (
    SELECT 1 FROM information_schema.columns
    WHERE table_schema = 'public' AND table_name = 'app_versions' AND column_name = 'version_code' AND data_type <> 'text'
  ) THEN
    ALTER TABLE public.app_versions
      ALTER COLUMN version_code TYPE text USING version_code::text;
  END IF;

  -- Alter min_version_required to text if needed
  IF EXISTS (
    SELECT 1 FROM information_schema.columns
    WHERE table_schema = 'public' AND table_name = 'app_versions' AND column_name = 'min_version_required' AND data_type <> 'text'
  ) THEN
    ALTER TABLE public.app_versions
      ALTER COLUMN min_version_required TYPE text USING min_version_required::text;
  END IF;

  -- Recreate unique index on version_code to ensure correct index type
  DROP INDEX IF EXISTS app_versions_version_code_idx;
  CREATE UNIQUE INDEX IF NOT EXISTS app_versions_version_code_idx ON public.app_versions (version_code);
END
$$;

-- Notes:
-- - Run this migration using the service_role key or from the Supabase SQL editor.
-- - After running, clients using string semantic versions (e.g., '0.1.1') will work.
