// server/api/config/klinik-ruang/[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 { kodeKlinik, namaKlinik, ruangList } = body;

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

  db.prepare(
    `UPDATE config_klinik_ruang SET
      kodeKlinik = ?, namaKlinik = ?, ruangList = ?,
      updatedAt = strftime('%s', 'now')
     WHERE id = ?`
  ).run(
    kodeKlinik ?? existing.kodeKlinik,
    namaKlinik ?? existing.namaKlinik,
    ruangList !== undefined ? JSON.stringify(ruangList) : existing.ruangList,
    id
  );

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