-- Migration 158: SAG work-order scan tokens and file provenance
-- Enables token-based auto-linking of scanned documents to cases.

CREATE TABLE IF NOT EXISTS sag_document_tokens (
    id SERIAL PRIMARY KEY,
    sag_id INTEGER NOT NULL REFERENCES sag_sager(id) ON DELETE CASCADE,
    token VARCHAR(120) NOT NULL UNIQUE,
    token_type VARCHAR(40) NOT NULL,
    hardware_id INTEGER REFERENCES hardware_assets(id) ON DELETE SET NULL,
    created_by_user_id INTEGER REFERENCES users(user_id) ON DELETE SET NULL,
    expires_at TIMESTAMP,
    consumed_at TIMESTAMP,
    consumed_email_id INTEGER REFERENCES email_messages(id) ON DELETE SET NULL,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT sag_document_tokens_type_check CHECK (token_type IN ('work_order', 'hardware_label'))
);

CREATE INDEX IF NOT EXISTS idx_sag_document_tokens_sag_id ON sag_document_tokens(sag_id);
CREATE INDEX IF NOT EXISTS idx_sag_document_tokens_token_type ON sag_document_tokens(token_type);
CREATE INDEX IF NOT EXISTS idx_sag_document_tokens_consumed ON sag_document_tokens(consumed_at);

ALTER TABLE sag_files
    ADD COLUMN IF NOT EXISTS source_email_id INTEGER REFERENCES email_messages(id) ON DELETE SET NULL,
    ADD COLUMN IF NOT EXISTS source_type VARCHAR(40),
    ADD COLUMN IF NOT EXISTS source_token VARCHAR(120);

UPDATE sag_files
SET source_type = 'upload'
WHERE source_type IS NULL;

CREATE INDEX IF NOT EXISTS idx_sag_files_source_email_id ON sag_files(source_email_id);
CREATE INDEX IF NOT EXISTS idx_sag_files_source_token ON sag_files(source_token);
