import { Router, Request, Response } from 'express';
import { prisma } from '../db/prisma';

const router = Router();

router.get('/', async (req: Request, res: Response) => {
  try {
    const nameFilter = req.query.name as string | undefined;

    const where = nameFilter
      ? { username: nameFilter.toLowerCase() }
      : { username: { not: null } };

    const users = await prisma.user.findMany({ where: where as any });

    const names: Record<string, string> = {};
    for (const user of users) {
      if (user.username) {
        names[user.username] = user.pubkey;
      }
    }

    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Content-Type', 'application/json');
    res.json({ names });
  } catch (err) {
    console.error('NIP-05 error:', err);
    res.status(500).json({ error: 'Internal server error' });
  }
});

export default router;
