-- ==========================================
-- 01: CREATE APPLICATION USERS
-- ==========================================
-- This script creates PostgreSQL users for the application
-- Runs as: postgres (superuser)

\echo '👤 Creating application users...'

-- ==========================================
-- BACKEND API USER (Primary Application Role)
-- ==========================================
DO $$
BEGIN
    IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'aurganize_backend_api') THEN
        CREATE USER aurganize_backend_api WITH
            PASSWORD 'dev_backend_pass_v6.2'  -- CHANGE IN PRODUCTION!
            LOGIN
            NOSUPERUSER
            NOCREATEDB
            NOCREATEROLE
            NOREPLICATION
            CONNECTION LIMIT 50;
        
        RAISE NOTICE '✅ User aurganize_backend_api created';
        RAISE NOTICE '⚠️  DEFAULT PASSWORD SET - CHANGE IN PRODUCTION!';
    ELSE
        RAISE NOTICE '⚠️  User aurganize_backend_api already exists';
    END IF;
END
$$;

-- ==========================================
-- READ-ONLY USER (Analytics/Reporting)
-- ==========================================
DO $$
BEGIN
    IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'aurganize_readonly') THEN
        CREATE USER aurganize_readonly WITH
            PASSWORD 'dev_readonly_pass_v6.2'  -- CHANGE IN PRODUCTION!
            LOGIN
            NOSUPERUSER
            NOCREATEDB
            NOCREATEROLE
            NOREPLICATION
            CONNECTION LIMIT 10;
        
        RAISE NOTICE '✅ User aurganize_readonly created';
    ELSE
        RAISE NOTICE '⚠️  User aurganize_readonly already exists';
    END IF;
END
$$;

-- ==========================================
-- VERIFY USERS CREATED
-- ==========================================
\echo ''
\echo '📋 Verifying users...'
SELECT 
    rolname AS username,
    rolcanlogin AS can_login,
    rolconnlimit AS connection_limit,
    CASE 
        WHEN rolsuper THEN 'superuser'
        ELSE 'regular user'
    END AS user_type
FROM pg_roles
WHERE rolname IN ('aurganize_backend_api', 'aurganize_readonly')
ORDER BY rolname;

\echo ''
\echo '✅ Users created successfully'
\echo ''