#!/bin/bash
# PostgreSQL initialization script for development environment
# Creates: workclub (application data), keycloak (Keycloak metadata)

set -e

# Create application database
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
    CREATE USER app WITH PASSWORD 'devpass';
    CREATE DATABASE workclub OWNER app;
    ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO app;
    ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO app;
EOSQL

# Create Keycloak database
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
    CREATE USER keycloak WITH PASSWORD 'keycloakpass';
    CREATE DATABASE keycloak OWNER keycloak;
    ALTER DEFAULT PRIVILEGES IN DATABASE keycloak GRANT ALL ON TABLES TO keycloak;
    ALTER DEFAULT PRIVILEGES IN DATABASE keycloak GRANT ALL ON SEQUENCES TO keycloak;
EOSQL

echo "PostgreSQL initialization complete: workclub and keycloak databases created"
