// server/api/config/anjungan/[id].put.ts
import { getConfigDb, parseConfigRow } from '~/server/utils/configDb';

export default defineEventHandler(async (event) => {
  const id = Number(getRouterParam(event, 'id'));
  if (!id) throw createError({ statusCode: 400, message: 'ID tidak valid' });

  const body = await readBody(event);
  const { namaAnjungan, jenisPasien, klinik } = body;

  const db = getConfigDb();
  const existing = db.prepare('SELECT * FROM config_anjungan WHERE id = ?').get(id) as any;
  if (!existing) throw createError({ statusCode: 404, message: 'Anjungan tidak ditemukan' });

  db.prepare(
    `UPDATE config_anjungan SET
      namaAnjungan = ?,
      jenisPasien = ?,
      klinik = ?,
      updatedAt = strftime('%s', 'now')
     WHERE id = ?`
  ).run(
    namaAnjungan ?? existing.namaAnjungan,
    jenisPasien ?? existing.jenisPasien,
    klinik !== undefined ? JSON.stringify(klinik) : existing.klinik,
    id
  );

  const updated = db.prepare('SELECT * FROM config_anjungan WHERE id = ?').get(id);
  return { success: true, data: parseConfigRow(updated), message: 'Anjungan berhasil diperbarui' };
});
