-- ============================================
-- 应付账款表 RLS 策略
-- ============================================

-- 启用 RLS
ALTER TABLE public.accounts_payable ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.accounts_payable_items ENABLE ROW LEVEL SECURITY;

-- 应付账款表策略
-- 采购商可以查看自己的应付账款
CREATE POLICY purchaser_select_ap ON public.accounts_payable
  FOR SELECT USING (purchaser_id = get_user_master_company_id());

-- 纺织厂可以查看与自己相关的应付账款
CREATE POLICY textile_select_ap ON public.accounts_payable
  FOR SELECT USING (textile_factory_id = get_user_master_company_id());

-- 采购商可以创建应付账款
CREATE POLICY purchaser_insert_ap ON public.accounts_payable
  FOR INSERT WITH CHECK (purchaser_id = get_user_master_company_id());

-- 采购商可以更新自己的应付账款
CREATE POLICY purchaser_update_ap ON public.accounts_payable
  FOR UPDATE USING (purchaser_id = get_user_master_company_id());

-- 应付账款明细表策略
-- 采购商可以查看自己的应付账款明细
CREATE POLICY purchaser_select_ap_items ON public.accounts_payable_items
  FOR SELECT USING (
    EXISTS (
      SELECT 1 FROM public.accounts_payable ap
      WHERE ap.id = accounts_payable_items.accounts_payable_id
      AND ap.purchaser_id = get_user_master_company_id()
    )
  );

-- 纺织厂可以查看与自己相关的应付账款明细
CREATE POLICY textile_select_ap_items ON public.accounts_payable_items
  FOR SELECT USING (
    EXISTS (
      SELECT 1 FROM public.accounts_payable ap
      WHERE ap.id = accounts_payable_items.accounts_payable_id
      AND ap.textile_factory_id = get_user_master_company_id()
    )
  );

-- 采购商可以创建应付账款明细
CREATE POLICY purchaser_insert_ap_items ON public.accounts_payable_items
  FOR INSERT WITH CHECK (
    EXISTS (
      SELECT 1 FROM public.accounts_payable ap
      WHERE ap.id = accounts_payable_items.accounts_payable_id
      AND ap.purchaser_id = get_user_master_company_id()
    )
  );

-- 采购商可以更新自己的应付账款明细
CREATE POLICY purchaser_update_ap_items ON public.accounts_payable_items
  FOR UPDATE USING (
    EXISTS (
      SELECT 1 FROM public.accounts_payable ap
      WHERE ap.id = accounts_payable_items.accounts_payable_id
      AND ap.purchaser_id = get_user_master_company_id()
    )
  );
