BEGIN;

-- =====================================================================================
-- Fix: hss_service_assignments INSERT RLS
-- Problem: consumers cannot insert assignments when auto-dispatching on order creation
-- because hss_service_assignments_staff_insert only allows the staff themselves.
-- Solution: allow the order owner (consumer) to insert assignments for their own orders.
-- =====================================================================================

DROP POLICY IF EXISTS hss_service_assignments_order_owner_insert ON public.hss_service_assignments;

CREATE POLICY hss_service_assignments_order_owner_insert
  ON public.hss_service_assignments
  FOR INSERT
  TO authenticated
  WITH CHECK (
    EXISTS (
      SELECT 1
      FROM public.hss_service_orders o
      WHERE o.id = order_id
        AND o.user_id IN (SELECT id FROM public.ak_users WHERE auth_id = auth.uid())
        AND o.deleted_at IS NULL
    )
  );

COMMENT ON POLICY hss_service_assignments_order_owner_insert
  ON public.hss_service_assignments IS '允许订单所有者（消费者）在下单时为其订单写入自动派单记录';

COMMIT;
