-- Fase 2 (Caja): gastos de caja. El negocio registra egresos del día (insumos,
-- pagos, etc.) y el cierre puede restarlos de las ventas (ingresos - gastos = neto).

create table if not exists public.gastos_caja (
  id uuid primary key default gen_random_uuid(),
  restaurante_id uuid not null references public.restaurantes(id) on delete cascade,
  concepto text not null,
  monto_usd numeric(12, 2) not null check (monto_usd >= 0),
  registrado_por uuid references public.perfiles(id) on delete set null,
  creado_en timestamptz not null default now(),
  archivado boolean not null default false
);

create index if not exists idx_gastos_caja_rest
  on public.gastos_caja (restaurante_id, archivado, creado_en desc);

alter table public.gastos_caja enable row level security;

-- El rol authenticated necesita el grant base; RLS filtra las filas.
grant select, insert, delete on public.gastos_caja to authenticated;

-- Solo el dueno/staff del restaurante gestiona SUS gastos (via su perfil).
drop policy if exists gastos_caja_select on public.gastos_caja;
create policy gastos_caja_select on public.gastos_caja
  for select to authenticated
  using (restaurante_id in (select restaurante_id from public.perfiles where id = auth.uid()));

drop policy if exists gastos_caja_insert on public.gastos_caja;
create policy gastos_caja_insert on public.gastos_caja
  for insert to authenticated
  with check (restaurante_id in (select restaurante_id from public.perfiles where id = auth.uid()));

drop policy if exists gastos_caja_delete on public.gastos_caja;
create policy gastos_caja_delete on public.gastos_caja
  for delete to authenticated
  using (restaurante_id in (select restaurante_id from public.perfiles where id = auth.uid()));
