// libSQL (Turso) client plus small query helpers.
import { createClient } from '@libsql/client';
import { config } from '../config.js';

export const db = createClient({
  url: config.databaseUrl,
  authToken: config.databaseAuthToken || undefined,
});

// Returns all rows as plain objects.
export async function query(sql, args = []) {
  const res = await db.execute({ sql, args });
  return res.rows;
}

// Returns the first row or null.
export async function queryOne(sql, args = []) {
  const rows = await query(sql, args);
  return rows.length ? rows[0] : null;
}

// Runs a write and returns the raw result (rowsAffected, lastInsertRowid).
export async function execute(sql, args = []) {
  return db.execute({ sql, args });
}
