-- Global Products for caching searches
CREATE TABLE IF NOT EXISTS global_products (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  wb_id TEXT UNIQUE NOT NULL,
  full_name TEXT NOT NULL,
  search_vector tsvector GENERATED ALWAYS AS (to_tsvector('simple', full_name)) STORED,
  image_hash TEXT,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT timezone('utc'::text, now())
);

-- Index for search vector
CREATE INDEX IF NOT EXISTS idx_global_products_search_vector ON global_products USING GIN (search_vector);

-- Enable RLS
ALTER TABLE global_products ENABLE ROW LEVEL SECURITY;

-- Policies for global_products
-- Enable Read Access for all users (SELECT)
DROP POLICY IF EXISTS "Enable Read Access for all users" ON global_products;
CREATE POLICY "Enable Read Access for all users"
ON global_products FOR SELECT
USING (true);

-- Disable Insert/Update for normal users (only Service Role/Admins)
DROP POLICY IF EXISTS "Enable Admin Insert/Update" ON global_products;
CREATE POLICY "Enable Admin Insert/Update"
ON global_products FOR ALL
USING (EXISTS (SELECT 1 FROM admin_users WHERE user_id = (SELECT auth.uid())))
WITH CHECK (EXISTS (SELECT 1 FROM admin_users WHERE user_id = (SELECT auth.uid())));
