-- Allow authenticated admin/dispatcher/it_staff profiles to write app_versions
-- while preserving service_role write access. This makes the web admin
-- uploader work for privileged users without exposing writes to all auth users.

-- Drop the restrictive service-only policy (if present)
DROP POLICY IF EXISTS "app_versions_service_write" ON public.app_versions;

-- Create a combined policy allowing either the service_role or a profile with
-- an elevated role to perform inserts/updates/deletes.
CREATE POLICY "app_versions_service_or_admin_write" ON public.app_versions
  FOR ALL
  USING (
    auth.role() = 'service_role'
    OR EXISTS (
      SELECT 1 FROM public.profiles p
      WHERE p.id = auth.uid() AND p.role IN ('admin', 'dispatcher', 'it_staff')
    )
  )
  WITH CHECK (
    auth.role() = 'service_role'
    OR EXISTS (
      SELECT 1 FROM public.profiles p
      WHERE p.id = auth.uid() AND p.role IN ('admin', 'dispatcher', 'it_staff')
    )
  );

-- Notes:
-- - Run this migration using the service_role key (or apply via the Supabase
--   SQL editor) so the new policy is created successfully.
-- - If your project stores roles in a different table or column, adjust the
--   `SELECT` accordingly.
