-- 更新 share_links 表的 RLS 策略

-- 删除旧的策略（如果存在）
DROP POLICY IF EXISTS share_links_select ON share_links;
DROP POLICY IF EXISTS share_links_insert ON share_links;
DROP POLICY IF EXISTS share_links_update ON share_links;

-- 创建查询策略：创建者可查看自己创建的链接，工厂可通过短码查看
CREATE POLICY share_links_select ON share_links
  FOR SELECT USING (
    created_by = auth.uid()
    OR EXISTS (
      SELECT 1 FROM profiles p
      WHERE p.id = auth.uid()
      AND p.company_id IN (
        SELECT purchaser_company_id FROM company_relationships 
        WHERE factory_company_id = p.company_id
      )
    )
    OR short_code IS NOT NULL  -- 允许通过短码查询（用于导入页面）
  );

-- 创建插入策略：仅登录用户可创建
CREATE POLICY share_links_insert ON share_links
  FOR INSERT WITH CHECK (
    auth.uid() IS NOT NULL
  );

-- 创建更新策略：创建者可更新，工厂可更新状态
CREATE POLICY share_links_update ON share_links
  FOR UPDATE USING (
    created_by = auth.uid()
    OR EXISTS (
      SELECT 1 FROM profiles p
      WHERE p.id = auth.uid()
      AND p.company_id IN (
        SELECT factory_company_id FROM company_relationships 
        WHERE purchaser_company_id = (
          SELECT purchaser_id FROM production_plans WHERE id = share_links.plan_id
        )
      )
    )
  );
