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

const router = Router();

router.post('/challenge', async (req: Request, res: Response) => {
  try {
    const { pubkey } = req.body;
    if (!pubkey || typeof pubkey !== 'string') {
      res.status(400).json({ error: 'pubkey is required' });
      return;
    }

    const challenge = authService.createChallenge(pubkey);
    res.json({ challenge });
  } catch (err) {
    console.error('Challenge error:', err);
    res.status(500).json({ error: 'Internal server error' });
  }
});

router.post('/verify', async (req: Request, res: Response) => {
  try {
    const { pubkey, signedEvent } = req.body;
    if (!pubkey || !signedEvent) {
      res.status(400).json({ error: 'pubkey and signedEvent are required' });
      return;
    }

    const valid = authService.verifySignature(pubkey, signedEvent);
    if (!valid) {
      res.status(401).json({ error: 'Invalid signature or expired challenge' });
      return;
    }

    const role = await authService.getRole(pubkey);

    const dbUser = await prisma.user.upsert({
      where: { pubkey },
      update: { role },
      create: { pubkey, role },
    });

    const token = authService.generateToken(pubkey, role);
    res.json({ token, user: { pubkey, role, username: dbUser.username ?? undefined } });
  } catch (err) {
    console.error('Verify error:', err);
    res.status(500).json({ error: 'Internal server error' });
  }
});

export default router;
