-- ==========================================
-- Migration 018: Model Visibility
-- ==========================================
-- Replace binary is_enabled with three-state visibility:
--   'enabled'  — visible to all users in model selector
--   'disabled' — hidden from everyone
--   'team'     — only available to team admins for building presets
-- ==========================================

-- Add new column (idempotent)
ALTER TABLE model_configs ADD COLUMN IF NOT EXISTS visibility VARCHAR(10) DEFAULT 'disabled';

-- Backfill from is_enabled if it still exists
DO $$ BEGIN
    IF EXISTS (
        SELECT 1 FROM information_schema.columns
        WHERE table_name = 'model_configs' AND column_name = 'is_enabled'
    ) THEN
        UPDATE model_configs SET visibility = CASE
            WHEN is_enabled = true THEN 'enabled'
            ELSE 'disabled'
        END;
        ALTER TABLE model_configs DROP COLUMN is_enabled;
    END IF;
END $$;

-- Ensure NOT NULL (safe: DEFAULT already covers new rows)
UPDATE model_configs SET visibility = 'disabled' WHERE visibility IS NULL;
ALTER TABLE model_configs ALTER COLUMN visibility SET NOT NULL;

-- Constraint (drop first for idempotency)
ALTER TABLE model_configs DROP CONSTRAINT IF EXISTS chk_model_visibility;
ALTER TABLE model_configs ADD CONSTRAINT chk_model_visibility
    CHECK (visibility IN ('enabled', 'disabled', 'team'));

COMMENT ON COLUMN model_configs.visibility IS 'enabled=all users, team=team admin presets only, disabled=hidden';
