import { NextResponse } from "next/server"
import { sql } from "@/lib/db"

export async function GET() {
  try {
    const settings = await sql`
      SELECT * FROM system_settings
    `

    // Convert array to object
    const settingsObj: Record<string, string> = {}
    settings.forEach((s: any) => {
      settingsObj[s.key] = s.value
    })

    return NextResponse.json(settingsObj)
  } catch (error) {
    console.error("Error fetching settings:", error)
    return NextResponse.json({})
  }
}

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

    // Update each setting
    for (const [key, value] of Object.entries(body)) {
      await sql`
        INSERT INTO system_settings (key, value)
        VALUES (${key}, ${String(value)})
        ON CONFLICT (key) DO UPDATE SET value = ${String(value)}, updated_at = NOW()
      `
    }

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error("Error updating settings:", error)
    return NextResponse.json({ error: "Failed to update settings" }, { status: 500 })
  }
}
