apiVersion: v1
kind: ConfigMap
metadata:
  name: postgres-init-config
  namespace: bakery-ia
  labels:
    app.kubernetes.io/component: database
    app.kubernetes.io/part-of: bakery-ia
data:
  init.sql: |
    -- Create required extensions
    CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
    CREATE EXTENSION IF NOT EXISTS "pg_stat_statements";
    CREATE EXTENSION IF NOT EXISTS "pgcrypto";

    -- Create monitoring user for SigNoz metrics collection
    -- This user will be created only if it doesn't already exist
    DO $$
    BEGIN
        IF NOT EXISTS (SELECT FROM pg_catalog.pg_user WHERE usename = 'monitoring') THEN
            CREATE USER monitoring WITH PASSWORD 'monitoring_369f9c001f242b07ef9e2826e17169ca';
            GRANT pg_monitor TO monitoring;
            GRANT SELECT ON pg_stat_database TO monitoring;
            RAISE NOTICE 'Created monitoring user for SigNoz metrics collection';
        ELSE
            -- User already exists, ensure it has the correct password and permissions
            ALTER USER monitoring WITH PASSWORD 'monitoring_369f9c001f242b07ef9e2826e17169ca';
            GRANT pg_monitor TO monitoring;
            GRANT SELECT ON pg_stat_database TO monitoring;
            RAISE NOTICE 'Updated monitoring user permissions for SigNoz metrics collection';
        END IF;
    END $$
    ;