-- 创建分类品牌关联表
CREATE TABLE public.category_brands (
  id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
  category_id UUID NOT NULL REFERENCES public.categories(id) ON DELETE CASCADE,
  brand_id UUID NOT NULL REFERENCES public.brands(id) ON DELETE CASCADE,
  created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
  UNIQUE(category_id, brand_id)
);

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

-- 所有人可以查看分类品牌关联
CREATE POLICY "Category brands are viewable by everyone" 
ON public.category_brands 
FOR SELECT 
USING (true);

-- 管理员可以管理分类品牌关联
CREATE POLICY "Admins can manage category brands" 
ON public.category_brands 
FOR ALL 
USING (
  EXISTS (
    SELECT 1 FROM public.profiles 
    WHERE user_id = auth.uid() AND role = 'admin'
  )
);

-- 创建索引提升查询性能
CREATE INDEX idx_category_brands_category_id ON public.category_brands(category_id);
CREATE INDEX idx_category_brands_brand_id ON public.category_brands(brand_id);