-- Migration: 111_system_settings.sql
-- Description: System settings table for runtime configuration
-- Created: 2024-12-14

CREATE TABLE IF NOT EXISTS system_settings (
  key VARCHAR(100) PRIMARY KEY,
  value TEXT NOT NULL,
  description TEXT,
  updated_at TIMESTAMPTZ DEFAULT NOW(),
  updated_by INTEGER REFERENCES users(id)
);

-- Task pool gate - controls whether workers can claim tasks
INSERT INTO system_settings (key, value, description) VALUES
  ('task_pool_open', 'true', 'When false, workers cannot claim new tasks from the pool')
ON CONFLICT (key) DO NOTHING;

-- Updated at trigger
CREATE OR REPLACE FUNCTION update_system_settings_updated_at()
RETURNS TRIGGER AS $$
BEGIN
  NEW.updated_at = NOW();
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

DROP TRIGGER IF EXISTS system_settings_updated_at ON system_settings;
CREATE TRIGGER system_settings_updated_at
  BEFORE UPDATE ON system_settings
  FOR EACH ROW
  EXECUTE FUNCTION update_system_settings_updated_at();

COMMENT ON TABLE system_settings IS 'Runtime configuration settings';
COMMENT ON COLUMN system_settings.key IS 'Setting name (e.g., task_pool_open)';
COMMENT ON COLUMN system_settings.value IS 'Setting value as string';
