-- Sag Module: Varekøb & Salg (case-linked sales items)

CREATE TABLE IF NOT EXISTS sag_salgsvarer (
    id SERIAL PRIMARY KEY,
    sag_id INTEGER NOT NULL REFERENCES sag_sager(id) ON DELETE CASCADE,
    type VARCHAR(20) NOT NULL DEFAULT 'sale', -- sale | purchase
    description TEXT NOT NULL,
    quantity NUMERIC(12, 2),
    unit VARCHAR(50),
    unit_price NUMERIC(12, 2),
    amount NUMERIC(12, 2) NOT NULL,
    currency VARCHAR(10) NOT NULL DEFAULT 'DKK',
    status VARCHAR(20) NOT NULL DEFAULT 'draft', -- draft | confirmed | cancelled
    line_date DATE,
    external_ref VARCHAR(100),
    created_at TIMESTAMP NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMP NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_sag_salgsvarer_sag_id ON sag_salgsvarer(sag_id);
CREATE INDEX IF NOT EXISTS idx_sag_salgsvarer_type ON sag_salgsvarer(type);
CREATE INDEX IF NOT EXISTS idx_sag_salgsvarer_status ON sag_salgsvarer(status);

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

DROP TRIGGER IF EXISTS trigger_sag_salgsvarer_updated_at ON sag_salgsvarer;
CREATE TRIGGER trigger_sag_salgsvarer_updated_at
BEFORE UPDATE ON sag_salgsvarer
FOR EACH ROW
EXECUTE FUNCTION update_sag_salgsvarer_updated_at();
