import { Router, Request, Response } from 'express';
import { prisma } from '../db/prisma';
import { requireAuth, requires } from '../middleware/auth';
import { nostrService } from '../services/nostr';

const router = Router();

router.post(
  '/fetch',
  requireAuth,
  requires('nostr_tools.use'),
  async (req: Request, res: Response) => {
    try {
      const { eventId, naddr } = req.body;
      if (!eventId && !naddr) {
        res.status(400).json({ error: 'eventId or naddr is required' });
        return;
      }

      let event = null;
      if (naddr) {
        event = await nostrService.fetchLongformEvent(naddr);
      } else if (eventId) {
        event = await nostrService.fetchEvent(eventId);
      }

      if (!event) {
        res.status(404).json({ error: 'Event not found on relays' });
        return;
      }

      res.json(event);
    } catch (err) {
      console.error('Fetch event error:', err);
      res.status(500).json({ error: 'Internal server error' });
    }
  }
);

router.post(
  '/cache/refresh',
  requireAuth,
  requires('nostr_tools.use'),
  async (_req: Request, res: Response) => {
    try {
      const cachedEvents = await prisma.nostrEventCache.findMany();
      let refreshed = 0;

      for (const cached of cachedEvents) {
        const event = await nostrService.fetchEvent(cached.eventId, true);
        if (event) refreshed++;
      }

      res.json({ refreshed, total: cachedEvents.length });
    } catch (err) {
      console.error('Cache refresh error:', err);
      res.status(500).json({ error: 'Internal server error' });
    }
  }
);

router.get(
  '/debug/:eventId',
  requireAuth,
  requires('nostr_tools.use'),
  async (req: Request, res: Response) => {
    try {
      const cached = await prisma.nostrEventCache.findUnique({
        where: { eventId: req.params.eventId as string },
      });

      if (!cached) {
        res.status(404).json({ error: 'Event not found in cache' });
        return;
      }

      res.json({
        ...cached,
        tags: JSON.parse(cached.tags),
      });
    } catch (err) {
      console.error('Debug event error:', err);
      res.status(500).json({ error: 'Internal server error' });
    }
  }
);

export default router;
