-- Ensure the buckets exist by inserting directly into the system table.
-- This matches the pattern used by older migrations and avoids relying on
-- optional SQL wrapper functions that may not be installed in all projects.

INSERT INTO storage.buckets (id, name, public)
VALUES ('apk_updates', 'apk_updates', true)
ON CONFLICT (id) DO NOTHING;

-- Ensure a `cors` column exists on storage.buckets for self-hosted installs
DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM information_schema.columns
    WHERE table_schema = 'storage' AND table_name = 'buckets' AND column_name = 'cors'
  ) THEN
    ALTER TABLE storage.buckets ADD COLUMN cors jsonb;
  END IF;
END
$$;

-- Set bucket to public (idempotent) and populate a basic CORS rule for local development.
-- Adjust or remove origins as appropriate for production.
-- NOTE: bucket public/CORS is intentionally left to dashboard or manual configuration
-- to ensure compatibility with self-hosted Supabase instances. If you need to
-- programmatically set `public` or `cors` on your environment, run an update
-- in the SQL editor with values appropriate for your deployment.

-- storage object policies for the apk_updates bucket
-- Create policies in the same style as other buckets (e.g. it_service_attachments)
DROP POLICY IF EXISTS "Authenticated users can upload apk_updates" ON storage.objects;
CREATE POLICY "Authenticated users can upload apk_updates"
  ON storage.objects FOR INSERT TO authenticated
  WITH CHECK (bucket_id = 'apk_updates');

DROP POLICY IF EXISTS "Authenticated users can read apk_updates" ON storage.objects;
CREATE POLICY "Authenticated users can read apk_updates"
  ON storage.objects FOR SELECT TO authenticated
  USING (bucket_id = 'apk_updates');

DROP POLICY IF EXISTS "Authenticated users can delete apk_updates" ON storage.objects;
CREATE POLICY "Authenticated users can delete apk_updates"
  ON storage.objects FOR DELETE TO authenticated
  USING (bucket_id = 'apk_updates');

-- Note: some self-hosted Supabase installations may require manual CORS configuration
-- via the dashboard. This migration sets a CORS value in the buckets table when
-- possible and marks the bucket public; if uploads still fail with CORS errors,
-- update the bucket settings in the Supabase UI to add the correct origin(s).