// server/api/config/screen/[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 { namaScreen, nomorScreen, klinik } = body;

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

  db.prepare(
    `UPDATE config_screen SET
      namaScreen = ?,
      nomorScreen = ?,
      klinik = ?,
      updatedAt = strftime('%s', 'now')
     WHERE id = ?`
  ).run(
    namaScreen ?? (existing as any).namaScreen,
    nomorScreen ?? (existing as any).nomorScreen,
    klinik !== undefined ? JSON.stringify(klinik) : (existing as any).klinik,
    id
  );

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