-- Fix duplicate categories and clean up product categories
-- This will consolidate similar categories and fix naming

-- Update products that reference categories we're about to merge
-- Update any references to 'Fertilizers' to point to 'Fertilizer' (if it exists)
UPDATE products SET category_id = (
    SELECT id FROM product_categories WHERE name = 'Fertilizer' LIMIT 1
) WHERE category_id = (
    SELECT id FROM product_categories WHERE name = 'Fertilizers' LIMIT 1
) AND EXISTS (SELECT 1 FROM product_categories WHERE name = 'Fertilizer');

-- Delete duplicate categories
DELETE FROM product_categories WHERE name IN ('Fertilizers') 
AND EXISTS (SELECT 1 FROM product_categories WHERE name = 'Fertilizer');

-- Update category names to be consistent (singular form)
UPDATE product_categories SET name = 'Herbicide' WHERE name = 'Herbicides';
UPDATE product_categories SET name = 'Fertilizer' WHERE name = 'Fertilizers';
UPDATE product_categories SET name = 'Fungicide' WHERE name = 'Fungicides';
UPDATE product_categories SET name = 'Insecticide' WHERE name = 'Insecticides';
UPDATE product_categories SET name = 'Surfactant' WHERE name = 'Surfactants';
UPDATE product_categories SET name = 'Adjuvant' WHERE name = 'Adjuvants';
UPDATE product_categories SET name = 'Growth Regulator' WHERE name = 'Growth Regulators';

-- Add any missing core categories
INSERT INTO product_categories (name, description) VALUES
('Herbicide', 'Products for weed control and prevention'),
('Fertilizer', 'Nutrients for lawn growth and health'),
('Fungicide', 'Products for disease prevention and treatment'),
('Insecticide', 'Products for insect control'),
('Pre-emergent', 'Products that prevent weeds from germinating'),
('Post-emergent', 'Products that kill existing weeds'),
('Growth Regulator', 'Products that modify plant growth'),
('Surfactant', 'Products that improve spray coverage and penetration'),
('Adjuvant', 'Products that enhance pesticide performance'),
('Seed', 'Grass seeds and seed treatments'),
('Soil Amendment', 'Products that improve soil conditions')
ON CONFLICT (name) DO NOTHING;