-- Migration 166: Bottom bar module activation and overrides

CREATE TABLE IF NOT EXISTS module_role_settings (
    id SERIAL PRIMARY KEY,
    module_name VARCHAR(100) NOT NULL,
    group_id INTEGER NOT NULL REFERENCES groups(id) ON DELETE CASCADE,
    enabled BOOLEAN NOT NULL DEFAULT TRUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    UNIQUE (module_name, group_id)
);

CREATE TABLE IF NOT EXISTS user_module_preferences (
    id SERIAL PRIMARY KEY,
    user_id INTEGER NOT NULL REFERENCES users(user_id) ON DELETE CASCADE,
    module_name VARCHAR(100) NOT NULL,
    enabled BOOLEAN,
    collapsed BOOLEAN NOT NULL DEFAULT FALSE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    UNIQUE (user_id, module_name)
);

INSERT INTO settings (key, value, category, description, value_type, is_public)
VALUES
    ('bottom_bar_enabled', 'false', 'bottom_bar', 'Enable or disable bottom bar globally', 'boolean', false)
ON CONFLICT (key) DO NOTHING;

-- Default role access: admins, managers and technicians enabled. viewers disabled.
INSERT INTO module_role_settings (module_name, group_id, enabled)
SELECT 'bottom_bar', g.id,
       CASE WHEN g.name IN ('Administrators', 'Managers', 'Technicians') THEN TRUE ELSE FALSE END
FROM groups g
ON CONFLICT (module_name, group_id) DO NOTHING;

CREATE INDEX IF NOT EXISTS idx_module_role_settings_module ON module_role_settings(module_name);
CREATE INDEX IF NOT EXISTS idx_user_module_preferences_user_module ON user_module_preferences(user_id, module_name);

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

DROP TRIGGER IF EXISTS module_role_settings_updated_at_trigger ON module_role_settings;
CREATE TRIGGER module_role_settings_updated_at_trigger
    BEFORE UPDATE ON module_role_settings
    FOR EACH ROW
    EXECUTE FUNCTION update_module_setting_updated_at();

DROP TRIGGER IF EXISTS user_module_preferences_updated_at_trigger ON user_module_preferences;
CREATE TRIGGER user_module_preferences_updated_at_trigger
    BEFORE UPDATE ON user_module_preferences
    FOR EACH ROW
    EXECUTE FUNCTION update_module_setting_updated_at();
