-- v2.8 Savings Reports

-- Add retail_price (MSRP) to inventory for savings calculation
ALTER TABLE inventory ADD COLUMN IF NOT EXISTS retail_price NUMERIC(12,2);
ALTER TABLE inventory ADD COLUMN IF NOT EXISTS reference_price NUMERIC(12,2); -- competitor price or market price

-- Track savings per sale item
ALTER TABLE sale_items ADD COLUMN IF NOT EXISTS retail_price NUMERIC(12,2);
ALTER TABLE sale_items ADD COLUMN IF NOT EXISTS savings_amount NUMERIC(12,2) DEFAULT 0;

-- Savings summary per sale
ALTER TABLE sales ADD COLUMN IF NOT EXISTS total_savings NUMERIC(12,2) DEFAULT 0;

-- Customer savings history (denormalized for quick lookup)
ALTER TABLE customers ADD COLUMN IF NOT EXISTS total_savings NUMERIC(12,2) DEFAULT 0;

-- Savings report view
CREATE OR REPLACE VIEW v_customer_savings AS
SELECT
    s.customer_id,
    c.name as customer_name,
    date_trunc('month', s.created_at) as month,
    COUNT(*) as orders_count,
    SUM(s.total) as total_spent,
    SUM(s.total_savings) as total_saved,
    AVG(s.total_savings / NULLIF(s.total, 0) * 100) as avg_savings_pct
FROM sales s
JOIN customers c ON s.customer_id = c.id
WHERE s.status = 'completed' AND s.total_savings > 0
GROUP BY s.customer_id, c.name, date_trunc('month', s.created_at)
ORDER BY month DESC, total_saved DESC;
