-- =====================================================================
-- 0000 Auth shim
-- Provides `auth.users`, `auth.uid()`, `auth.role()`, `auth.jwt()` so
-- the application migrations (which were written for Supabase) run
-- unmodified. The backend sets `request.jwt.claim.sub` (and friends)
-- per request from the verified JWT, then `set local role authenticated`.
-- =====================================================================

create extension if not exists "pgcrypto";
create extension if not exists "citext";

-- Supabase ships these roles; create them if missing (e.g. plain Postgres).
do $$ begin
  if not exists (select 1 from pg_roles where rolname = 'anon') then
    create role anon nologin noinherit;
  end if;
  if not exists (select 1 from pg_roles where rolname = 'authenticated') then
    create role authenticated nologin noinherit;
  end if;
  if not exists (select 1 from pg_roles where rolname = 'service_role') then
    create role service_role nologin noinherit bypassrls;
  end if;
end $$;

create schema if not exists auth;

-- Minimal `auth.users` compatible with FKs in app migrations.
create table if not exists auth.users (
  id              uuid primary key default gen_random_uuid(),
  email           citext unique,
  password_hash   text not null,
  full_name       text,
  is_system_admin boolean not null default false,
  is_active       boolean not null default true,
  created_at      timestamptz not null default now(),
  last_login_at   timestamptz
);

create or replace function auth.uid()
returns uuid
language sql
stable
as $$
  select nullif(current_setting('request.jwt.claim.sub', true), '')::uuid
$$;

create or replace function auth.role()
returns text
language sql
stable
as $$
  select coalesce(nullif(current_setting('request.jwt.claim.role', true), ''), 'anon')
$$;

create or replace function auth.jwt()
returns jsonb
language sql
stable
as $$
  select coalesce(nullif(current_setting('request.jwt.claims', true), '')::jsonb, '{}'::jsonb)
$$;

grant usage on schema auth to authenticated, anon, service_role;
grant select on auth.users to authenticated, service_role;
