-- Fase 2 (CRM): lista de clientes del restaurante (quien ha pedido, cuantas veces,
-- cuanto y cuando). Se arma sola desde los pedidos, agregada por telefono.

create table if not exists public.clientes (
  id uuid primary key default gen_random_uuid(),
  restaurante_id uuid not null references public.restaurantes(id) on delete cascade,
  telefono text not null,
  nombre text,
  pedidos_count integer not null default 0,
  total_usd numeric(12, 2) not null default 0,
  ultimo_pedido_en timestamptz not null default now(),
  creado_en timestamptz not null default now(),
  unique (restaurante_id, telefono)
);
create index if not exists idx_clientes_rest on public.clientes (restaurante_id, pedidos_count desc, ultimo_pedido_en desc);

alter table public.clientes enable row level security;
-- El frontend solo LEE; el trigger (security definer) escribe.
grant select on public.clientes to authenticated;
drop policy if exists clientes_select on public.clientes;
create policy clientes_select on public.clientes
  for select to authenticated
  using (restaurante_id in (select restaurante_id from public.perfiles where id = auth.uid()));

-- Acumula el cliente desde los pedidos. Best-effort: nunca rompe el pedido.
create or replace function public.tg_crm_cliente()
returns trigger
language plpgsql
security definer
set search_path to 'public'
as $$
begin
  begin
    if TG_OP = 'INSERT' and new.cliente_telefono is not null and length(trim(new.cliente_telefono)) > 0 then
      insert into public.clientes (restaurante_id, telefono, nombre, pedidos_count, total_usd, ultimo_pedido_en)
        values (new.restaurante_id, new.cliente_telefono, new.cliente_nombre, 1, coalesce(new.total_usd, 0), now())
      on conflict (restaurante_id, telefono) do update
        set pedidos_count = public.clientes.pedidos_count + 1,
            nombre = coalesce(excluded.nombre, public.clientes.nombre),
            total_usd = public.clientes.total_usd + excluded.total_usd,
            ultimo_pedido_en = now();
    elsif TG_OP = 'UPDATE'
      and new.total_usd is distinct from old.total_usd
      and new.cliente_telefono is not null and length(trim(new.cliente_telefono)) > 0 then
      -- crear_pedido finaliza el total tras insertar: ajusta con la diferencia.
      update public.clientes
         set total_usd = greatest(0, total_usd + (coalesce(new.total_usd, 0) - coalesce(old.total_usd, 0)))
       where restaurante_id = new.restaurante_id and telefono = new.cliente_telefono;
    end if;
  exception when others then
    null;
  end;
  return null;
end;
$$;

drop trigger if exists trg_crm_cliente on public.pedidos;
create trigger trg_crm_cliente
  after insert or update on public.pedidos
  for each row execute function public.tg_crm_cliente();
