CREATE TABLE IF NOT EXISTS pipeline_stages (
    id SERIAL PRIMARY KEY,
    name VARCHAR(50) NOT NULL UNIQUE,
    color VARCHAR(20) DEFAULT '#0f4c75',
    sort_order INTEGER DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

INSERT INTO pipeline_stages (name, color, sort_order)
SELECT 'Lead', '#6c757d', 10
WHERE NOT EXISTS (SELECT 1 FROM pipeline_stages WHERE LOWER(name) = 'lead');

INSERT INTO pipeline_stages (name, color, sort_order)
SELECT 'Kontakt', '#17a2b8', 20
WHERE NOT EXISTS (SELECT 1 FROM pipeline_stages WHERE LOWER(name) = 'kontakt');

INSERT INTO pipeline_stages (name, color, sort_order)
SELECT 'Tilbud', '#ffc107', 30
WHERE NOT EXISTS (SELECT 1 FROM pipeline_stages WHERE LOWER(name) = 'tilbud');

INSERT INTO pipeline_stages (name, color, sort_order)
SELECT 'Forhandling', '#fd7e14', 40
WHERE NOT EXISTS (SELECT 1 FROM pipeline_stages WHERE LOWER(name) = 'forhandling');

INSERT INTO pipeline_stages (name, color, sort_order)
SELECT 'Vundet', '#28a745', 50
WHERE NOT EXISTS (SELECT 1 FROM pipeline_stages WHERE LOWER(name) = 'vundet');

INSERT INTO pipeline_stages (name, color, sort_order)
SELECT 'Tabt', '#dc3545', 60
WHERE NOT EXISTS (SELECT 1 FROM pipeline_stages WHERE LOWER(name) = 'tabt');

ALTER TABLE sag_sager
    ADD COLUMN IF NOT EXISTS pipeline_amount DECIMAL(15,2),
    ADD COLUMN IF NOT EXISTS pipeline_probability INTEGER DEFAULT 0,
    ADD COLUMN IF NOT EXISTS pipeline_stage_id INTEGER REFERENCES pipeline_stages(id) ON DELETE SET NULL;

CREATE INDEX IF NOT EXISTS idx_sag_sager_pipeline_stage_id ON sag_sager(pipeline_stage_id);
