-- =====================================================================================
-- RLS: 医养执行端 Delivery 安全策略升级
-- 位置：docs/sql/20_rls/delivery/ak_delivery_rls_v2.sql
-- 对象类型：RLS 策略
-- 版本：v2
-- 说明：保留管理端通过 SECURITY DEFINER RPC 管理，补充执行人员本人直读自己档案。
-- =====================================================================================

ALTER TABLE public.ml_delivery_staff ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.ml_delivery_stations ENABLE ROW LEVEL SECURITY;

-- 清理旧策略
DROP POLICY IF EXISTS delivery_staff_self_select ON public.ml_delivery_staff;
DROP POLICY IF EXISTS delivery_stations_select_active ON public.ml_delivery_stations;

-- 1. 执行人员本人可直读自己的未删除档案
CREATE POLICY delivery_staff_self_select
  ON public.ml_delivery_staff
  FOR SELECT
  TO authenticated
  USING (
    deleted_at IS NULL
    AND EXISTS (
      SELECT 1
      FROM public.ak_users u
      WHERE u.id = ml_delivery_staff.uid
        AND u.auth_id = auth.uid()
    )
  );

-- 2. 提货点/机构对前台保持只读，仅返回启用且未删除数据
CREATE POLICY delivery_stations_select_active
  ON public.ml_delivery_stations
  FOR SELECT
  TO anon, authenticated
  USING (status = 1 AND deleted_at IS NULL);

-- 3. 其余直连写操作默认不开放，管理端统一走 SECURITY DEFINER RPC
