-- Migration: Enhance Products Table with Color Variants and Rich Text
-- Created: 2025-12-19
-- Description: Adds color variants, rich text description fields, and product images table

-- Add new columns to products table (if they don't exist)
ALTER TABLE products 
ADD COLUMN IF NOT EXISTS weight DECIMAL(10,2),
ADD COLUMN IF NOT EXISTS dimensions VARCHAR(100),
ADD COLUMN IF NOT EXISTS material VARCHAR(255),
ADD COLUMN IF NOT EXISTS metakeywords TEXT;

-- Create product images table with color variant support
CREATE TABLE IF NOT EXISTS product_images (
  id TEXT PRIMARY KEY DEFAULT replace(gen_random_uuid()::text, '-', ''),
  product_id TEXT NOT NULL,
  image_url VARCHAR(500) NOT NULL,
  color_variant VARCHAR(100),
  alt_text VARCHAR(255),
  display_order INTEGER DEFAULT 0,
  is_primary BOOLEAN DEFAULT FALSE,
  created_at TIMESTAMP DEFAULT NOW(),
  CONSTRAINT fk_product_images_product FOREIGN KEY (product_id) REFERENCES products(id) ON DELETE CASCADE
);

-- Create indexes for better performance
CREATE INDEX IF NOT EXISTS idx_product_images_product_id ON product_images(product_id);
CREATE INDEX IF NOT EXISTS idx_product_images_color ON product_images(color_variant);
CREATE INDEX IF NOT EXISTS idx_product_images_primary ON product_images(product_id, is_primary) WHERE is_primary = TRUE;

-- Add comments for documentation
COMMENT ON TABLE product_images IS 'Stores product images with color variant associations';
COMMENT ON COLUMN product_images.color_variant IS 'Color variant name (e.g., "Red", "Blue", "Black")';
COMMENT ON COLUMN product_images.is_primary IS 'Indicates if this is the primary image for the product/variant';

-- Update products table slug generation for existing products (if needed)
UPDATE products 
SET slug = LOWER(REGEXP_REPLACE(REGEXP_REPLACE(name, '[^a-zA-Z0-9\s-]', '', 'g'), '\s+', '-', 'g'))
WHERE slug IS NULL OR slug = '';

-- Ensure unique slug
CREATE UNIQUE INDEX IF NOT EXISTS idx_products_slug_unique ON products(slug) WHERE slug IS NOT NULL AND slug != '';

-- Add default short description from existing description (if needed)
UPDATE products 
SET shortdescription = LEFT(description, 200)
WHERE (shortdescription IS NULL OR shortdescription = '') AND description IS NOT NULL AND description != '';
