-- Create table that holds the latest version information for the
-- self‑hosted Android update mechanism.  Mobile clients query this table
-- anonymously and compare the returned `version_code`/`min_version_required`
-- against their own build number.

CREATE TABLE IF NOT EXISTS public.app_versions (
  version_code text NOT NULL,
  min_version_required text NOT NULL,
  download_url text NOT NULL,
  release_notes text DEFAULT ''
);

-- index for quick ordering by version_code
CREATE UNIQUE INDEX IF NOT EXISTS app_versions_version_code_idx
  ON public.app_versions (version_code);

-- Enable realtime for clients if desired
ALTER PUBLICATION supabase_realtime ADD TABLE public.app_versions;

-- Row level security and simple policies
ALTER TABLE public.app_versions ENABLE ROW LEVEL SECURITY;

-- allow everyone (including anon) to read the table
DROP POLICY IF EXISTS "app_versions_public_read" ON public.app_versions;
CREATE POLICY "app_versions_public_read" ON public.app_versions
  FOR SELECT USING (true);

-- only the service role (e.g. migrations or trusted server) may write
DROP POLICY IF EXISTS "app_versions_service_write" ON public.app_versions;
CREATE POLICY "app_versions_service_write" ON public.app_versions
  FOR ALL USING (auth.role() = 'service_role')
  WITH CHECK (auth.role() = 'service_role');
