// server/api/config/screen.post.ts
import { getConfigDb, parseConfigRow } from '~/server/utils/configDb';

export default defineEventHandler(async (event) => {
  const body = await readBody(event);
  const { namaScreen, nomorScreen, klinik = [] } = body;

  if (!namaScreen || !nomorScreen) {
    throw createError({ statusCode: 400, message: 'namaScreen dan nomorScreen wajib diisi' });
  }

  const db = getConfigDb();
  try {
    const result = db.prepare(
      `INSERT INTO config_screen (namaScreen, nomorScreen, klinik) VALUES (?, ?, ?)`
    ).run(namaScreen, nomorScreen, JSON.stringify(klinik));

    const newRow = db.prepare('SELECT * FROM config_screen WHERE id = ?').get(result.lastInsertRowid);
    return { success: true, data: parseConfigRow(newRow), message: `Screen ${namaScreen} berhasil ditambahkan` };
  } catch (e: any) {
    if (e.message?.includes('UNIQUE')) {
      throw createError({ statusCode: 409, message: `nomorScreen "${nomorScreen}" sudah digunakan` });
    }
    throw createError({ statusCode: 500, message: e.message });
  }
});
