import { NextRequest, NextResponse } from 'next/server' import pool from '@/lib/appDb' import { generateId } from '@/lib/config' import { reloadBackupCrons } from '@/lib/cronWorker' import { requireAuth } from '@/lib/auth' // GET configs and logs for a dbId export async function GET(req: NextRequest) { const err = await requireAuth(req) if (err) return err const { searchParams } = new URL(req.url) const dbId = searchParams.get('dbId') if (!dbId) return NextResponse.json({ error: 'Missing dbId' }, { status: 400 }) try { const configRes = await pool.query(`SELECT * FROM backup_configs WHERE db_id = $1 LIMIT 1`, [dbId]) const logsRes = await pool.query(`SELECT * FROM backup_logs WHERE db_id = $1 ORDER BY ts DESC LIMIT 50`, [dbId]) return NextResponse.json({ config: configRes.rows[0] || null, logs: logsRes.rows.map(r => ({ ...r, file_size: Number(r.file_size), ts: Number(r.ts) })) }) } catch (e: any) { return NextResponse.json({ error: e.message }, { status: 500 }) } } // Create or update a backup config export async function POST(req: NextRequest) { const err = await requireAuth(req) if (err) return err try { const body = await req.json() const { db_id, schedule, connection_id, cloud_type, credentials, gdrive_folder_id } = body if (!db_id || !schedule) { return NextResponse.json({ error: 'db_id ve schedule zorunlu' }, { status: 400 }) } // connection_id VEYA credentials zorunlu if (!connection_id && !credentials) { return NextResponse.json({ error: 'connection_id veya credentials gerekli' }, { status: 400 }) } const existing = await pool.query(`SELECT id FROM backup_configs WHERE db_id = $1`, [db_id]) if (existing.rows.length > 0) { await pool.query( `UPDATE backup_configs SET schedule=$1, cloud_type=$2, credentials=$3, gdrive_folder_id=$4, connection_id=$5 WHERE db_id=$6`, [schedule, cloud_type || '', credentials || '', gdrive_folder_id || null, connection_id || null, db_id] ) } else { await pool.query( `INSERT INTO backup_configs (id, db_id, schedule, cloud_type, credentials, gdrive_folder_id, connection_id) VALUES ($1, $2, $3, $4, $5, $6, $7)`, [generateId(), db_id, schedule, cloud_type || '', credentials || '', gdrive_folder_id || null, connection_id || null] ) } // Reload crons in memory await reloadBackupCrons() return NextResponse.json({ ok: true }) } catch (e: any) { return NextResponse.json({ error: e.message }, { status: 500 }) } } // Delete backup config export async function DELETE(req: NextRequest) { const err = await requireAuth(req) if (err) return err try { const body = await req.json() const { db_id } = body if (!db_id) return NextResponse.json({ error: 'Missing dbId' }, { status: 400 }) await pool.query(`DELETE FROM backup_configs WHERE db_id = $1`, [db_id]) await reloadBackupCrons() return NextResponse.json({ ok: true }) } catch (e: any) { return NextResponse.json({ error: e.message }, { status: 500 }) } }