-- Create roles that Clerk passes in the JWT `role` claim
-- PostgREST attempts to assume these roles when making requests.
-- We create them and grant them the standard authenticated role permissions.

DO $$
BEGIN
  IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'admin') THEN
    CREATE ROLE admin NOLOGIN;
    GRANT authenticated TO admin;
  END IF;

  IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'teacher') THEN
    CREATE ROLE teacher NOLOGIN;
    GRANT authenticated TO teacher;
  END IF;

  IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'student') THEN
    CREATE ROLE student NOLOGIN;
    GRANT authenticated TO student;
  END IF;

  IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'parent') THEN
    CREATE ROLE parent NOLOGIN;
    GRANT authenticated TO parent;
  END IF;
END $$;

-- Grant the roles to the authenticator role so PostgREST can switch to them
GRANT admin TO authenticator;
GRANT teacher TO authenticator;
GRANT student TO authenticator;
GRANT parent TO authenticator;
