-- ============================================================================
-- Feature Check Script - Diagnose vor/nach Migration
-- ============================================================================
-- Usage: psql -U mitai_dev -d mitai_dev -f check_features.sql
-- ============================================================================

\echo '=== CURRENT FEATURES ==='
SELECT id, name, category, limit_type, reset_period, default_limit, active
FROM features
ORDER BY category, id;

\echo ''
\echo '=== TIER LIMITS MATRIX ==='
SELECT
    f.id as feature,
    f.category,
    MAX(CASE WHEN tl.tier_id = 'free' THEN COALESCE(tl.limit_value::text, '∞') END) as free,
    MAX(CASE WHEN tl.tier_id = 'basic' THEN COALESCE(tl.limit_value::text, '∞') END) as basic,
    MAX(CASE WHEN tl.tier_id = 'premium' THEN COALESCE(tl.limit_value::text, '∞') END) as premium,
    MAX(CASE WHEN tl.tier_id = 'selfhosted' THEN COALESCE(tl.limit_value::text, '∞') END) as selfhosted
FROM features f
LEFT JOIN tier_limits tl ON f.id = tl.feature_id
GROUP BY f.id, f.category
ORDER BY f.category, f.id;

\echo ''
\echo '=== FEATURE COUNT BY CATEGORY ==='
SELECT category, COUNT(*) as count
FROM features
WHERE active = true
GROUP BY category
ORDER BY category;

\echo ''
\echo '=== ORPHANED TIER LIMITS (feature not exists) ==='
SELECT tl.tier_id, tl.feature_id, tl.limit_value
FROM tier_limits tl
LEFT JOIN features f ON tl.feature_id = f.id
WHERE f.id IS NULL;

\echo ''
\echo '=== USER FEATURE USAGE (current usage tracking) ==='
SELECT
    p.name as user,
    ufu.feature_id,
    ufu.usage_count,
    ufu.reset_at
FROM user_feature_usage ufu
JOIN profiles p ON ufu.profile_id = p.id
ORDER BY p.name, ufu.feature_id;
