-- =============================================================================
-- postgres/audit/init.sql
-- Runs once on first container start (postgres-audit).
-- Creates login users for audit_writer and audit_maintainer roles.
-- Role privileges are granted by V2 Flyway migration.
-- =============================================================================

-- audit_writer_login: login user that maps to audit_writer role
-- Used by HAPI audit datasource. INSERT only on audit schema.
CREATE USER audit_writer_login WITH
    NOSUPERUSER
    NOCREATEDB
    NOCREATEROLE
    NOINHERIT           -- does not automatically inherit role privileges
    LOGIN
    CONNECTION LIMIT 20 -- hard cap: prevents connection exhaustion
    PASSWORD 'PLACEHOLDER_REPLACED_BY_ENTRYPOINT';
-- NOTE: Actual password is set by the postgres Docker entrypoint
-- reading AUDIT_DB_WRITER_PASSWORD from environment. This CREATE USER
-- is a template — the entrypoint rewrites the password on init.
-- In practice, use the POSTGRES_* env vars pattern and manage user
-- creation via an init script that reads env vars:

-- Grant the audit_writer role to the login user
-- (role created by V2 migration — this runs after migration on first start)
-- This GRANT is idempotent — safe to re-run.
DO $$
BEGIN
    IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'audit_writer') THEN
        GRANT audit_writer TO audit_writer_login;
    END IF;
END
$$;

-- audit_maintainer_login: login user for partition maintenance cron job
CREATE USER audit_maintainer_login WITH
    NOSUPERUSER
    NOCREATEDB
    NOCREATEROLE
    NOINHERIT
    LOGIN
    CONNECTION LIMIT 5
    PASSWORD 'PLACEHOLDER_REPLACED_BY_ENTRYPOINT';

DO $$
BEGIN
    IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'audit_maintainer') THEN
        GRANT audit_maintainer TO audit_maintainer_login;
    END IF;
END
$$;

-- Grant connect on database to both login users
GRANT CONNECT ON DATABASE auditdb TO audit_writer_login;
GRANT CONNECT ON DATABASE auditdb TO audit_maintainer_login;
