-- Migration 084: Sag (Case) Files and Linked Emails
-- Adds support for uploading files and linking emails to cases (Sager)

-- Files linked to a Case
CREATE TABLE IF NOT EXISTS sag_files (
    id SERIAL PRIMARY KEY,
    sag_id INTEGER NOT NULL REFERENCES sag_sager(id) ON DELETE CASCADE,
    filename VARCHAR(255) NOT NULL,
    content_type VARCHAR(100),
    size_bytes INTEGER,
    stored_name TEXT NOT NULL,
    uploaded_by_user_id INTEGER REFERENCES users(user_id) ON DELETE SET NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX IF NOT EXISTS idx_sag_files_sag_id ON sag_files(sag_id);
COMMENT ON TABLE sag_files IS 'Files uploaded directly to the Case.';

-- Emails linked to a Case (Many-to-Many)
CREATE TABLE IF NOT EXISTS sag_emails (
    sag_id INTEGER REFERENCES sag_sager(id) ON DELETE CASCADE,
    email_id INTEGER REFERENCES email_messages(id) ON DELETE CASCADE,
    created_at TIMESTAMPTZ DEFAULT NOW(),
    PRIMARY KEY (sag_id, email_id)
);

COMMENT ON TABLE sag_emails IS 'Emails linked to the Case.';
