-- ============================================================
-- Gustito Express — Registro libre del restaurante (self-service).
-- El dueno se registra (usuario comensal por defecto) y con esta funcion
-- crea su negocio: se le asigna rol 'dueno', se crea el restaurante y su enlace unico.
-- ============================================================

-- Genera un slug unico a partir del nombre (sin acentos, minusculas, con guiones).
create or replace function public.generar_slug_unico(p_nombre text)
returns text language plpgsql security definer set search_path = public as $$
declare
  v_base text;
  v_slug text;
  v_n    int := 1;
begin
  v_base := lower(p_nombre);
  v_base := translate(v_base, 'áàäâéèëêíìïîóòöôúùüûñ', 'aaaaeeeeiiiioooouuuun');
  v_base := regexp_replace(v_base, '[^a-z0-9]+', '-', 'g');
  v_base := trim(both '-' from v_base);
  if v_base = '' then v_base := 'negocio'; end if;
  v_slug := v_base;
  while exists (select 1 from public.restaurantes where slug = v_slug) loop
    v_n := v_n + 1;
    v_slug := v_base || '-' || v_n;
  end loop;
  return v_slug;
end $$;
grant execute on function public.generar_slug_unico(text) to authenticated;

-- Crea el restaurante del dueno recien registrado (registro libre: queda activo, sin publicar).
create or replace function public.crear_restaurante(p_nombre text, p_telefono text default null)
returns table (restaurante_id uuid, slug text)
language plpgsql security definer set search_path = public as $$
declare
  v_uid  uuid := auth.uid();
  v_slug text;
  v_id   uuid;
begin
  if v_uid is null then
    raise exception 'Debes iniciar sesion';
  end if;
  if exists (
    select 1 from public.perfiles p
    where p.id = v_uid and p.rol = 'dueno' and p.restaurante_id is not null
  ) then
    raise exception 'Ya tienes un restaurante registrado';
  end if;
  if coalesce(length(trim(p_nombre)), 0) < 2 then
    raise exception 'El nombre del negocio es muy corto';
  end if;

  v_slug := public.generar_slug_unico(p_nombre);

  insert into public.restaurantes (slug, nombre, telefono, tasa_bs, activo, publicado, onboarding_completo)
    values (v_slug, trim(p_nombre), p_telefono,
            (select tasa_bs from public.tasa_cambio where id = 1), true, false, false)
    returning id into v_id;

  update public.perfiles
     set rol = 'dueno',
         restaurante_id = v_id,
         telefono = coalesce(telefono, p_telefono)
   where id = v_uid;

  return query select v_id, v_slug;
end $$;
grant execute on function public.crear_restaurante(text, text) to authenticated;
