-- =========================================================================
-- Migration 017: Opportunity Line Items
-- =========================================================================

CREATE TABLE IF NOT EXISTS pipeline_opportunity_lines (
    id SERIAL PRIMARY KEY,
    opportunity_id INTEGER NOT NULL REFERENCES pipeline_opportunities(id) ON DELETE CASCADE,
    product_number VARCHAR(100),
    name VARCHAR(255) NOT NULL,
    description TEXT,
    quantity INTEGER NOT NULL DEFAULT 1,
    unit_price NUMERIC(12, 2) NOT NULL DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX IF NOT EXISTS idx_pipeline_opportunity_lines_opportunity_id ON pipeline_opportunity_lines(opportunity_id);
CREATE INDEX IF NOT EXISTS idx_pipeline_opportunity_lines_product_number ON pipeline_opportunity_lines(product_number);

CREATE OR REPLACE FUNCTION update_pipeline_opportunity_lines_updated_at()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = CURRENT_TIMESTAMP;
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER update_pipeline_opportunity_lines_updated_at
BEFORE UPDATE ON pipeline_opportunity_lines
FOR EACH ROW
EXECUTE FUNCTION update_pipeline_opportunity_lines_updated_at();
