import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';

export async function GET() {
  try {
    const settings = await prisma.setting.findMany();
    return NextResponse.json({ settings });
  } catch (error) {
    return NextResponse.json({ error: 'Failed to fetch settings' }, { status: 500 });
  }
}

export async function POST(req: Request) {
  try {
    const { settings } = await req.json();
    
    // settings is expected to be { GOOGLE_PLACES_API_KEY: '...', ... }
    const updatePromises = Object.entries(settings).map(([key, value]) => {
      return prisma.setting.upsert({
        where: { key },
        update: { value: value as string },
        create: { key, value: value as string }
      });
    });

    await Promise.all(updatePromises);

    // Also log this activity
    await prisma.activityLog.create({
      data: {
        action: 'UPDATE_SETTINGS',
        details: 'System parameters and credentials updated'
      }
    });

    return NextResponse.json({ success: true });
  } catch (error) {
    return NextResponse.json({ error: 'Failed to update settings' }, { status: 500 });
  }
}
