import { error, json, type RequestHandler } from "@sveltejs/kit";
import { getDb } from "$lib/database";

export const GET: RequestHandler = async ({ url }) => {
  const npub = url.searchParams.get("npub");

  if (!npub) {
    throw error(400, "Missing npub parameter");
  }

  try {
    const db = await getDb();
    const result = await db.execute(
      "SELECT username FROM users WHERE npub = ?",
      [npub],
    );

    if (result.rows.length > 0) {
      return json({
        username: result.rows[0].username,
        exists: true,
      });
    } else {
      return json({
        username: null,
        exists: false,
      });
    }
  } catch (err) {
    console.error("Database error:", err);
    throw error(500, "Database error");
  }
};
