-- 0055_user_permission_overrides.sql
-- ----------------------------------------------------------------------------
-- Per-user permission overrides layered on top of the role's baseline.
-- Effective permission = role[resource][action]
--                        |> apply port_role_overrides for that port
--                        |> apply user_permission_overrides for (user, port)
--
-- A user override entry is OPTIONAL - most users will never have one.
-- When present, the JSONB blob is a Partial<RolePermissions> map where any
-- explicitly-set leaf wins over the inherited value (true forces grant,
-- false forces deny, missing → inherit).

CREATE TABLE IF NOT EXISTS user_permission_overrides (
  id TEXT PRIMARY KEY DEFAULT gen_random_uuid()::text,
  user_id TEXT NOT NULL,
  port_id TEXT NOT NULL REFERENCES ports(id) ON DELETE CASCADE,
  permission_overrides JSONB NOT NULL DEFAULT '{}'::jsonb,
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE UNIQUE INDEX IF NOT EXISTS idx_user_perm_overrides_user_port
  ON user_permission_overrides (user_id, port_id);

CREATE INDEX IF NOT EXISTS idx_user_perm_overrides_user
  ON user_permission_overrides (user_id);
