-- Migration: Add category hierarchy (parent-child structure)
-- Date: 2026-01-28
-- Description: Adds parent_id to categories for 4 main groups + subcategories

-- Add parent_id column
ALTER TABLE categories ADD COLUMN IF NOT EXISTS parent_id INTEGER REFERENCES categories(id);
ALTER TABLE categories ADD COLUMN IF NOT EXISTS display_order INTEGER DEFAULT 0;

-- Create index for parent lookup
CREATE INDEX IF NOT EXISTS idx_categories_parent_id ON categories(parent_id);

-- Insert 4 main categories (parents)
INSERT INTO categories (name, slug, description, parent_id, display_order)
VALUES
    ('Usługi', 'uslugi', 'Firmy usługowe - IT, doradztwo, marketing, prawo, finanse', NULL, 1),
    ('Budownictwo', 'budownictwo-grupa', 'Budownictwo, instalacje, architektura, nieruchomości', NULL, 2),
    ('Handel', 'handel', 'Handel, hurtownie, motoryzacja, hotelarstwo', NULL, 3),
    ('Produkcja', 'produkcja-grupa', 'Produkcja, wytwarzanie, rolnictwo', NULL, 4)
ON CONFLICT (slug) DO NOTHING;

-- Get IDs of main categories (will be used in next migration step)
-- Note: The actual parent assignment will be done via Python script
-- because we need to know the exact IDs

-- Comments
COMMENT ON COLUMN categories.parent_id IS 'Parent category ID for hierarchical structure (NULL = main category)';
COMMENT ON COLUMN categories.display_order IS 'Order for display in UI';

-- Grant permissions
GRANT ALL ON TABLE categories TO nordabiz_app;
