
CREATE TABLE public.guard_locations (
  guard_id UUID PRIMARY KEY REFERENCES public.security_guards(id) ON DELETE CASCADE,
  latitude DOUBLE PRECISION NOT NULL,
  longitude DOUBLE PRECISION NOT NULL,
  accuracy DOUBLE PRECISION,
  heading DOUBLE PRECISION,
  speed DOUBLE PRECISION,
  battery INTEGER,
  updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

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

ALTER TABLE public.guard_locations ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Authenticated can view live locations"
  ON public.guard_locations FOR SELECT
  TO authenticated USING (true);

CREATE POLICY "Authenticated can upsert live locations"
  ON public.guard_locations FOR INSERT
  TO authenticated WITH CHECK (true);

CREATE POLICY "Authenticated can update live locations"
  ON public.guard_locations FOR UPDATE
  TO authenticated USING (true) WITH CHECK (true);

CREATE TRIGGER trg_guard_locations_updated
  BEFORE UPDATE ON public.guard_locations
  FOR EACH ROW EXECUTE FUNCTION public.tg_set_updated_at();

ALTER PUBLICATION supabase_realtime ADD TABLE public.guard_locations;
ALTER TABLE public.guard_locations REPLICA IDENTITY FULL;
