-- Initialize all databases
-- Check if databases exist before creating them
DO $$
BEGIN
    IF NOT EXISTS (SELECT FROM pg_database WHERE datname = 'n8n_db') THEN
        CREATE DATABASE n8n_db;
    END IF;
END
$$;

DO $$
BEGIN
    IF NOT EXISTS (SELECT FROM pg_database WHERE datname = 'gitea_db') THEN
        CREATE DATABASE gitea_db;
    END IF;
END
$$;

-- dev_pipeline is already created by POSTGRES_DB environment variable

-- 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";
