import { FastifyInstance } from 'fastify';
import { DbService } from '../services/db.service.js';

const SETTING_KEYS = [
  'enrich_metadata',
  'enrich_artist_images',
  'enrich_cover_art',
  'enrich_genres',
  'enrich_lyrics',
  'enrich_artist_similarity',
  'enrich_audio_analysis',
] as const;

type SettingKey = typeof SETTING_KEYS[number];

export default async function settingsRoutes(fastify: FastifyInstance, options: { dbService: DbService }) {
  const { dbService } = options;

  // GET /api/settings — return all settings as { key: value } map.
  fastify.get('/settings', async () => {
    const rows = await dbService.pgClient.query('SELECT key, value FROM settings');
    const map: Record<string, string> = {};
    for (const row of rows.rows) {
      map[row.key] = row.value;
    }
    return map;
  });

  // PUT /api/settings/:key — update one setting.
  // Validates the key against known keys and the value as 'true'/'false'.
  fastify.put<{ Params: { key: string }; Body: { value: string } }>(
    '/settings/:key',
    async (request, reply) => {
      const { key } = request.params;
      const { value } = request.body;

      if (!SETTING_KEYS.includes(key as SettingKey)) {
        return reply.code(400).send({ error: `Unknown setting: ${key}` });
      }
      if (value !== 'true' && value !== 'false') {
        return reply.code(400).send({ error: 'Value must be "true" or "false"' });
      }

      await dbService.pgClient.query(
        `INSERT INTO settings (key, value, updated_at)
         VALUES ($1, $2, NOW())
         ON CONFLICT (key) DO UPDATE SET value = $2, updated_at = NOW()`,
        [key, value]
      );

      return { status: 'ok', key, value };
    }
  );
}
