#!/bin/bash
# PostgreSQL initialization script
# Creates the konstruct_app application role with limited privileges.
# The postgres superuser role is NEVER used by application code.
set -e

psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
    DO \$\$
    BEGIN
        IF NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = 'konstruct_app') THEN
            CREATE ROLE konstruct_app WITH LOGIN PASSWORD 'konstruct_dev';
        END IF;
    END
    \$\$;

    GRANT CONNECT ON DATABASE konstruct TO konstruct_app;
    GRANT USAGE ON SCHEMA public TO konstruct_app;
EOSQL

echo "konstruct_app role created successfully."
