-- Migration 002: Add case-to-contacts and case-to-customers relationships

-- Link cases to contacts
CREATE TABLE IF NOT EXISTS sag_kontakter (
    id SERIAL PRIMARY KEY,
    sag_id INTEGER NOT NULL REFERENCES sag_sager(id) ON DELETE CASCADE,
    contact_id INTEGER NOT NULL,
    role VARCHAR(100),
    created_at TIMESTAMP NOT NULL DEFAULT NOW(),
    deleted_at TIMESTAMP
);

-- Link cases to customers (explicit table for many-to-many relationship)
CREATE TABLE IF NOT EXISTS sag_kunder (
    id SERIAL PRIMARY KEY,
    sag_id INTEGER NOT NULL REFERENCES sag_sager(id) ON DELETE CASCADE,
    customer_id INTEGER NOT NULL,
    role VARCHAR(100),
    created_at TIMESTAMP NOT NULL DEFAULT NOW(),
    deleted_at TIMESTAMP
);

-- Indexes for performance
CREATE INDEX IF NOT EXISTS idx_sag_kontakter_sag_id ON sag_kontakter(sag_id) WHERE deleted_at IS NULL;
CREATE INDEX IF NOT EXISTS idx_sag_kontakter_contact_id ON sag_kontakter(contact_id) WHERE deleted_at IS NULL;
CREATE INDEX IF NOT EXISTS idx_sag_kunder_sag_id ON sag_kunder(sag_id) WHERE deleted_at IS NULL;
CREATE INDEX IF NOT EXISTS idx_sag_kunder_customer_id ON sag_kunder(customer_id) WHERE deleted_at IS NULL;
