-- Create Keycloak schema if it doesn't exist
create schema if not exists keycloak;

-- Create Keycloak user if it doesn't exist
do $$
begin
    if not exists (select 1 from pg_roles where rolname = 'keycloak') then
        create user keycloak with password 'keycloak';
    end if;
end
$$;

-- Grant schema usage and ownership to Keycloak user
alter schema keycloak owner to keycloak;
grant usage on schema keycloak to keycloak;

-- Grant all privileges on all tables in keycloak schema to keycloak user
grant all privileges on all tables in schema keycloak to keycloak;

-- Grant all privileges on all sequences in keycloak schema to keycloak user
grant all privileges on all sequences in schema keycloak to keycloak;

-- Set default privileges for future tables and sequences
alter default privileges in schema keycloak grant all on tables to keycloak;
alter default privileges in schema keycloak grant all on sequences to keycloak; 