-- Create pipeline_admin user for existing database
-- This script can be run manually on existing PostgreSQL instances

-- Create pipeline_admin user if it doesn't exist
DO $$
BEGIN
    IF NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = 'pipeline_admin') THEN
        CREATE USER pipeline_admin WITH PASSWORD 'secure_pipeline_2024';
        RAISE NOTICE 'Created user pipeline_admin';
    ELSE
        -- Update password in case it's different
        ALTER USER pipeline_admin WITH PASSWORD 'secure_pipeline_2024';
        RAISE NOTICE 'Updated password for existing user pipeline_admin';
    END IF;
END
$$;

-- Ensure pipeline_admin has superuser privileges (needed for migrations)
ALTER USER pipeline_admin WITH SUPERUSER;

-- Grant all privileges on existing databases
GRANT ALL PRIVILEGES ON DATABASE postgres TO pipeline_admin;
GRANT ALL PRIVILEGES ON DATABASE dev_pipeline TO pipeline_admin;

-- Connect to dev_pipeline and grant schema permissions
\c dev_pipeline;
GRANT ALL ON SCHEMA public TO pipeline_admin;
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO pipeline_admin;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO pipeline_admin;
GRANT ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public TO pipeline_admin;

-- Set default privileges for future objects
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO pipeline_admin;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO pipeline_admin;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON FUNCTIONS TO pipeline_admin;

\echo 'Pipeline admin user setup completed successfully'
