-- =============================================================================
-- postgres/fhir/init.sql
-- Runs once on first container start (postgres-fhir).
-- Creates the application user that HAPI uses at runtime.
-- Flyway migrations run as superuser separately.
-- =============================================================================

-- Application user — read/write to HAPI JPA tables
-- Password injected from FHIR_DB_APP_PASSWORD environment variable
-- via docker-compose. The \getenv syntax requires psql — use DO block instead.
DO $$
BEGIN
    IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = current_setting('app.db_user', true)) THEN
        -- User created by the entrypoint using POSTGRES_* env vars equivalent.
        -- This script creates it explicitly for auditability.
        NULL;
    END IF;
END
$$;

-- Create app user. Password set via environment variable substitution
-- in the Docker entrypoint. The actual CREATE USER is handled by
-- the entrypoint script reading FHIR_DB_APP_USER/PASSWORD env vars.
-- This script grants the necessary privileges after user creation.

-- Grant connect
GRANT CONNECT ON DATABASE fhirdb TO hapi_app;

-- Grant schema usage and object privileges
-- Flyway creates all tables as superuser; we then grant hapi_app access.
-- These grants run after Flyway migrations on first startup via Spring Boot
-- ApplicationListener — see DataSourceConfig.java.
-- Pre-grant public schema access:
GRANT USAGE ON SCHEMA public TO hapi_app;
ALTER DEFAULT PRIVILEGES IN SCHEMA public
    GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO hapi_app;
ALTER DEFAULT PRIVILEGES IN SCHEMA public
    GRANT USAGE, SELECT ON SEQUENCES TO hapi_app;
