-- Update user equipment for better spreader support
-- Note: we already have 'manufacturer' and 'model' columns, so let's use those
-- Add brand as alias for manufacturer for consistency with new API
ALTER TABLE user_equipment 
ADD COLUMN IF NOT EXISTS brand VARCHAR(100),
ADD COLUMN IF NOT EXISTS notes TEXT;

-- Copy existing manufacturer data to brand field for consistency
UPDATE user_equipment SET brand = manufacturer WHERE brand IS NULL AND manufacturer IS NOT NULL;

-- Create table to store product-specific spreader settings
-- This links products to specific spreader settings
CREATE TABLE IF NOT EXISTS product_spreader_settings (
    id SERIAL PRIMARY KEY,
    product_id INTEGER REFERENCES products(id) ON DELETE CASCADE,
    user_product_id INTEGER REFERENCES user_products(id) ON DELETE CASCADE,
    spreader_brand VARCHAR(100) NOT NULL,
    spreader_model VARCHAR(100),
    setting_value VARCHAR(20) NOT NULL,
    rate_description VARCHAR(200), -- e.g., "1 lb nitrogen per 1000 sq ft"
    notes TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    
    -- Ensure we have either product_id or user_product_id, but not both
    CHECK (
        (product_id IS NOT NULL AND user_product_id IS NULL) OR
        (product_id IS NULL AND user_product_id IS NOT NULL)
    )
);

-- Create indexes for better performance
CREATE INDEX IF NOT EXISTS idx_product_spreader_settings_product ON product_spreader_settings(product_id);
CREATE INDEX IF NOT EXISTS idx_product_spreader_settings_user_product ON product_spreader_settings(user_product_id);
CREATE INDEX IF NOT EXISTS idx_product_spreader_settings_brand ON product_spreader_settings(spreader_brand);
CREATE INDEX IF NOT EXISTS idx_user_equipment_brand_model ON user_equipment(brand, model);

-- Add trigger to update updated_at timestamp
CREATE OR REPLACE FUNCTION update_product_spreader_settings_updated_at()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = CURRENT_TIMESTAMP;
    RETURN NEW;
END;
$$ language 'plpgsql';

DROP TRIGGER IF EXISTS update_product_spreader_settings_updated_at_trigger ON product_spreader_settings;
CREATE TRIGGER update_product_spreader_settings_updated_at_trigger
    BEFORE UPDATE ON product_spreader_settings
    FOR EACH ROW
    EXECUTE PROCEDURE update_product_spreader_settings_updated_at();

-- Drop the old spreader_settings table since we're using a different approach
DROP TABLE IF EXISTS spreader_settings;

SELECT 'Updated spreader system for user-defined spreaders and product settings!' as migration_status;