-- ============================================================================
-- GLM HUB — HOTFIX DE ACCESO AUTOMÁTICO POR DOMINIO
-- ============================================================================
-- Ejecutar una sola vez en Supabase Studio > SQL Editor.
--
-- Resultado esperado:
--   * Todo usuario autenticado con @gomezleemarketing.com entra como Usuario.
--   * La ausencia de una fila en glm_hub_authorized_users NO bloquea el acceso.
--   * La tabla queda reservada para administradores y bloqueos excepcionales.
-- ============================================================================

begin;

comment on table public.glm_hub_authorized_users is
  'Excepciones del GLM Hub: administradores activos y usuarios bloqueados. Los usuarios corporativos normales no requieren registro.';

-- Cada usuario puede consultar únicamente su propia excepción. Una respuesta
-- vacía significa que es un Usuario normal del dominio corporativo.
drop policy if exists "GLM Hub users can read only their active access"
  on public.glm_hub_authorized_users;
drop policy if exists "GLM Hub users can read their own control record"
  on public.glm_hub_authorized_users;

create policy "GLM Hub users can read their own control record"
on public.glm_hub_authorized_users
for select
to authenticated
using (
  email = lower(coalesce((select auth.jwt() ->> 'email'), ''))
);

-- La ausencia de registro significa acceso normal como Usuario.
create or replace function public.glm_hub_is_active_user()
returns boolean
language plpgsql
stable
security definer
set search_path = ''
as $$
declare
  v_email text;
begin
  v_email := lower(coalesce(auth.jwt() ->> 'email', ''));

  return
    auth.uid() is not null
    and v_email ~ '^[a-z0-9.!#$%&''*+/=?^_`{|}~-]+@gomezleemarketing\.com$'
    and not exists (
      select 1
      from public.glm_hub_authorized_users as access
      where access.email = v_email
        and access.is_active = false
    );
end;
$$;

-- Solo una fila activa con role = admin concede funciones administrativas.
create or replace function public.glm_hub_is_admin()
returns boolean
language plpgsql
stable
security definer
set search_path = ''
as $$
declare
  v_email text;
begin
  v_email := lower(coalesce(auth.jwt() ->> 'email', ''));

  return
    auth.uid() is not null
    and exists (
      select 1
      from public.glm_hub_authorized_users as access
      where access.email = v_email
        and access.role = 'admin'
        and access.is_active = true
    );
end;
$$;

alter function public.glm_hub_is_active_user() owner to postgres;
alter function public.glm_hub_is_admin() owner to postgres;

revoke all on function public.glm_hub_is_active_user() from public, anon;
revoke all on function public.glm_hub_is_admin() from public, anon;
grant execute on function public.glm_hub_is_active_user() to authenticated;
grant execute on function public.glm_hub_is_admin() to authenticated;
grant execute on function public.glm_hub_is_active_user() to service_role;
grant execute on function public.glm_hub_is_admin() to service_role;

-- Limpia registros normales antiguos. Se conservan administradores y bloqueos.
delete from public.glm_hub_authorized_users
where role = 'member'
  and is_active = true;

notify pgrst, 'reload schema';

commit;

-- VERIFICACIÓN OPCIONAL:
-- select public.glm_hub_is_active_user() as puede_entrar,
--        public.glm_hub_is_admin() as es_administrador;
