import { NextResponse } from 'next/server';
import { getDb, getSetting, upsertSetting } from '@/lib/db';

export const dynamic = 'force-dynamic';

export async function GET() {
  try {
    const db = getDb();
    const rows = db.prepare('SELECT key, value FROM settings').all() as Array<{ key: string; value: string }>;
    const settings: Record<string, string> = {};
    for (const row of rows) {
      settings[row.key] = row.value;
    }
    return NextResponse.json(settings);
  } catch (error) {
    console.error('[settings] GET failed:', error);
    return NextResponse.json({ error: 'Failed to load settings' }, { status: 500 });
  }
}

export async function PUT(request: Request) {
  try {
    const body = await request.json();

    if (!body || typeof body !== 'object') {
      return NextResponse.json({ error: 'Request body must be a JSON object' }, { status: 400 });
    }

    const entries = Object.entries(body);
    if (entries.length === 0) {
      return NextResponse.json({ error: 'No settings provided' }, { status: 400 });
    }

    for (const [key, value] of entries) {
      if (typeof key !== 'string' || key.trim().length === 0) continue;
      upsertSetting(key, String(value));
    }

    return NextResponse.json({ success: true, updated: entries.length });
  } catch (error) {
    console.error('[settings] PUT failed:', error);
    return NextResponse.json({ error: 'Failed to save settings' }, { status: 500 });
  }
}
