CREATE TABLE IF NOT EXISTS public.address_geocodes (
  id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
  address_key TEXT NOT NULL UNIQUE,
  address TEXT NOT NULL,
  lat DOUBLE PRECISION,
  lng DOUBLE PRECISION,
  source TEXT,
  display_name TEXT,
  not_found BOOLEAN NOT NULL DEFAULT false,
  created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
  updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_address_geocodes_key ON public.address_geocodes (address_key);

ALTER TABLE public.address_geocodes ENABLE ROW LEVEL SECURITY;

DROP POLICY IF EXISTS "Anyone can read geocode cache" ON public.address_geocodes;
CREATE POLICY "Anyone can read geocode cache"
  ON public.address_geocodes FOR SELECT
  USING (true);

DROP POLICY IF EXISTS "Authenticated can write geocode cache" ON public.address_geocodes;
CREATE POLICY "Authenticated can write geocode cache"
  ON public.address_geocodes FOR INSERT
  TO authenticated
  WITH CHECK (true);

DROP POLICY IF EXISTS "Authenticated can update geocode cache" ON public.address_geocodes;
CREATE POLICY "Authenticated can update geocode cache"
  ON public.address_geocodes FOR UPDATE
  TO authenticated
  USING (true)
  WITH CHECK (true);

DROP TRIGGER IF EXISTS update_address_geocodes_updated_at ON public.address_geocodes;
CREATE TRIGGER update_address_geocodes_updated_at
  BEFORE UPDATE ON public.address_geocodes
  FOR EACH ROW
  EXECUTE FUNCTION public.update_updated_at_column();