-- Migration 093: Case module visibility preferences

CREATE TABLE IF NOT EXISTS sag_module_prefs (
    id SERIAL PRIMARY KEY,
    sag_id INTEGER NOT NULL REFERENCES sag_sager(id) ON DELETE CASCADE,
    module_key VARCHAR(50) NOT NULL,
    is_enabled BOOLEAN NOT NULL DEFAULT TRUE,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    UNIQUE (sag_id, module_key)
);

CREATE INDEX IF NOT EXISTS idx_sag_module_prefs_sag ON sag_module_prefs(sag_id);

-- Trigger to auto-update updated_at
CREATE OR REPLACE FUNCTION update_sag_module_prefs_updated_at()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = CURRENT_TIMESTAMP;
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

DROP TRIGGER IF EXISTS update_sag_module_prefs_updated_at ON sag_module_prefs;
CREATE TRIGGER update_sag_module_prefs_updated_at
    BEFORE UPDATE ON sag_module_prefs
    FOR EACH ROW
    EXECUTE FUNCTION update_sag_module_prefs_updated_at();
