
CREATE TABLE public.supervisor_locations (
  user_id UUID PRIMARY KEY REFERENCES auth.users(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.supervisor_locations TO authenticated;
GRANT ALL ON public.supervisor_locations TO service_role;

ALTER TABLE public.supervisor_locations ENABLE ROW LEVEL SECURITY;

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

CREATE POLICY "Users can insert their own supervisor location"
  ON public.supervisor_locations FOR INSERT
  TO authenticated WITH CHECK (auth.uid() = user_id);

CREATE POLICY "Users can update their own supervisor location"
  ON public.supervisor_locations FOR UPDATE
  TO authenticated USING (auth.uid() = user_id) WITH CHECK (auth.uid() = user_id);

CREATE POLICY "Users can delete their own supervisor location"
  ON public.supervisor_locations FOR DELETE
  TO authenticated USING (auth.uid() = user_id);

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

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