CREATE TABLE public.coletas (
  id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  usuario TEXT NOT NULL,
  codigo_barras TEXT NOT NULL,
  inicio_coleta TIMESTAMPTZ NOT NULL DEFAULT now(),
  fim_coleta TIMESTAMPTZ,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

GRANT SELECT, INSERT, UPDATE ON public.coletas TO anon;
GRANT SELECT, INSERT, UPDATE, DELETE ON public.coletas TO authenticated;
GRANT ALL ON public.coletas TO service_role;

ALTER TABLE public.coletas ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Coletas sao visiveis publicamente" ON public.coletas FOR SELECT TO anon, authenticated USING (true);
CREATE POLICY "Qualquer um pode criar coleta" ON public.coletas FOR INSERT TO anon, authenticated WITH CHECK (true);
CREATE POLICY "Qualquer um pode atualizar coleta" ON public.coletas FOR UPDATE TO anon, authenticated USING (true) WITH CHECK (true);

CREATE INDEX idx_coletas_usuario_abertas ON public.coletas (usuario) WHERE fim_coleta IS NULL;