-- Fase 2 (Inventario): existencias por producto + descuento automatico al vender.

alter table public.productos
  add column if not exists controla_stock boolean not null default false,
  add column if not exists stock integer not null default 0,
  add column if not exists stock_minimo integer not null default 0;

-- Descontar stock al vender: al insertarse un item de pedido, baja el stock del
-- producto (solo si ese producto controla stock). Best-effort: NUNCA rompe la
-- creacion del pedido (va en un bloque exception).
create or replace function public.tg_descontar_stock()
returns trigger
language plpgsql
security definer
set search_path to 'public'
as $$
begin
  begin
    update public.productos
       set stock = greatest(0, stock - coalesce(new.cantidad, 1))
     where id = new.producto_id
       and controla_stock = true;
  exception when others then
    null;
  end;
  return null;
end;
$$;

drop trigger if exists trg_descontar_stock on public.pedido_items;
create trigger trg_descontar_stock
  after insert on public.pedido_items
  for each row execute function public.tg_descontar_stock();
