-- ============================================
-- 修复成品表RLS策略，让采购商能查看关联计划的成品
-- ============================================

-- 删除旧的SELECT策略
DROP POLICY IF EXISTS company_select_finished_products ON finished_products;

-- 创建新的SELECT策略：允许成品所属公司或通过水洗计划关联的采购商查看
CREATE POLICY company_select_finished_products ON finished_products
  FOR SELECT USING (
    company_id = get_user_master_company_id()
    OR EXISTS (
      SELECT 1 FROM washing_plans wp
      WHERE wp.id = finished_products.washing_plan_id
      AND wp.company_id = get_user_master_company_id()
    )
  );

-- 更新策略：只允许成品所属公司更新
DROP POLICY IF EXISTS company_update_finished_products ON finished_products;
CREATE POLICY company_update_finished_products ON finished_products
  FOR UPDATE USING (company_id = get_user_master_company_id());

-- 删除策略：只允许成品所属公司删除
DROP POLICY IF EXISTS company_delete_finished_products ON finished_products;
CREATE POLICY company_delete_finished_products ON finished_products
  FOR DELETE USING (company_id = get_user_master_company_id());

-- 添加注释说明
COMMENT ON POLICY company_select_finished_products ON finished_products IS '允许成品所属公司或通过水洗计划关联的采购商查看成品';

-- 同时修复成品出入库记录的RLS策略
DROP POLICY IF EXISTS company_select_finished_inventory ON finished_product_inventory_records;

CREATE POLICY company_select_finished_inventory ON finished_product_inventory_records
  FOR SELECT USING (
    company_id = get_user_master_company_id()
    OR EXISTS (
      SELECT 1 FROM finished_products fp
      WHERE fp.id = finished_product_inventory_records.finished_product_id
      AND EXISTS (
        SELECT 1 FROM washing_plans wp
        WHERE wp.id = fp.washing_plan_id
        AND wp.company_id = get_user_master_company_id()
      )
    )
  );

COMMENT ON POLICY company_select_finished_inventory ON finished_product_inventory_records IS '允许成品所属公司或关联的采购商查看出入库记录';
