-- Initialize all databases
CREATE DATABASE n8n_db;
CREATE DATABASE gitea_db;
CREATE DATABASE dev_pipeline;

-- Create users
CREATE USER n8n_user WITH PASSWORD 'n8n_secure_2024';
CREATE USER gitea_user WITH PASSWORD 'gitea_secure_2024';
-- 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';
    END IF;
END
$$;

-- Grant permissions
GRANT ALL PRIVILEGES ON DATABASE n8n_db TO n8n_user;
GRANT ALL PRIVILEGES ON DATABASE gitea_db TO gitea_user;
GRANT ALL PRIVILEGES ON DATABASE dev_pipeline TO pipeline_admin;

-- Enable extensions on main database
\c dev_pipeline;
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
CREATE EXTENSION IF NOT EXISTS "pgcrypto";
CREATE EXTENSION IF NOT EXISTS "pg_stat_statements";

-- Create basic monitoring
\c postgres;
CREATE EXTENSION IF NOT EXISTS "pg_stat_statements";
