import { NextRequest, NextResponse } from 'next/server' import { getServerSession } from 'next-auth' import { authOptions } from '@/lib/auth' import sql from '@/lib/db' export async function POST( req: NextRequest, { params }: { params: Promise<{ id: string }> } ) { const session = await getServerSession(authOptions) if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) const { id } = await params const body = await req.json() const { environment_id, environment, entries, overwrite = true } = body if (!environment_id || !Array.isArray(entries) || entries.length === 0) { return NextResponse.json( { error: 'environment_id ve en az bir config girişi gereklidir.' }, { status: 400 } ) } const actor = session.user?.name ?? 'admin' const insertedOrUpdated: any[] = [] try { await sql.begin(async (tx) => { for (const item of entries) { if (!item.key || item.value === undefined) continue const formattedKey = item.key.trim().toUpperCase().replace(/\s+/g, '_') const formattedValue = String(item.value).trim() const formattedType = item.type || 'text' const formattedDesc = item.description || null if (overwrite) { const [res] = await tx` INSERT INTO config_entries (environment_id, key, value, type, description) VALUES (${environment_id}, ${formattedKey}, ${formattedValue}, ${formattedType}, ${formattedDesc}) ON CONFLICT (environment_id, key) DO UPDATE SET value = EXCLUDED.value, type = EXCLUDED.type, description = COALESCE(EXCLUDED.description, config_entries.description), updated_at = NOW() RETURNING * ` insertedOrUpdated.push(res) } else { const [res] = await tx` INSERT INTO config_entries (environment_id, key, value, type, description) VALUES (${environment_id}, ${formattedKey}, ${formattedValue}, ${formattedType}, ${formattedDesc}) ON CONFLICT (environment_id, key) DO NOTHING RETURNING * ` if (res) insertedOrUpdated.push(res) } } // Record batch audit log if (insertedOrUpdated.length > 0) { await tx` INSERT INTO audit_logs (app_id, environment, action, key, actor) VALUES ( ${id}, ${environment}, 'create', ${`${insertedOrUpdated.length} adet config toplu aktarıldı`}, ${actor} ) ` } }) return NextResponse.json({ success: true, count: insertedOrUpdated.length, entries: insertedOrUpdated, }) } catch (err: any) { return NextResponse.json({ error: err.message }, { status: 500 }) } }