#!/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 workclub WITH PASSWORD 'dev_password_change_in_production';
    CREATE DATABASE workclub OWNER workclub;
    ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO workclub;
    ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO workclub;
EOSQL

# Create app_admin role for RLS bypass (used by SeedDataService)
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "workclub" <<-EOSQL
    CREATE ROLE app_admin;
    GRANT app_admin TO workclub WITH INHERIT FALSE, SET TRUE;
    ALTER DEFAULT PRIVILEGES FOR ROLE workclub IN SCHEMA public GRANT ALL ON TABLES TO app_admin;
    ALTER DEFAULT PRIVILEGES FOR ROLE workclub IN SCHEMA public GRANT ALL ON SEQUENCES TO app_admin;
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;
EOSQL

# Grant privileges in keycloak database
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "keycloak" <<-EOSQL
    GRANT ALL ON SCHEMA public TO keycloak;
    ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO keycloak;
    ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO keycloak;
EOSQL

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