// server/api/config/antrean-masuk-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, loket } = body;

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

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

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