import { requireAuth } from '../auth.js'
import { pool } from '../db.js'

const ALLOWED_KEYS = new Set(['forecasting_url', 'forecasting_api_key'])

export async function settingsRoutes(fastify) {
  fastify.addHook('preHandler', requireAuth)

  fastify.get('/api/settings', async (request, reply) => {
    if (!request.user?.is_admin) return reply.status(403).send({ error: 'Admin only' })
    const res = await pool.query('SELECT key, value, updated_at FROM app_settings ORDER BY key')
    return { settings: res.rows }
  })

  fastify.put('/api/settings', async (request, reply) => {
    if (!request.user?.is_admin) return reply.status(403).send({ error: 'Admin only' })
    const { settings } = request.body || {}
    if (!Array.isArray(settings)) return reply.status(400).send({ error: 'settings must be an array' })

    for (const { key, value } of settings) {
      if (!ALLOWED_KEYS.has(key)) continue
      await pool.query(
        `INSERT INTO app_settings (key, value, updated_at) VALUES ($1, $2, NOW())
         ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = NOW()`,
        [key, value ?? '']
      )
    }
    return { ok: true }
  })
}
