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

const router = Router();

router.get(
  '/public',
  async (_req: Request, res: Response) => {
    try {
      const relays = await prisma.relay.findMany({
        where: { active: true },
        orderBy: { priority: 'asc' },
      });
      res.json({ relays: relays.map((r) => r.url) });
    } catch (err) {
      console.error('Public relays error:', err);
      res.status(500).json({ error: 'Internal server error' });
    }
  }
);

router.get(
  '/',
  requireAuth,
  requires('relays.manage'),
  async (_req: Request, res: Response) => {
    try {
      const relays = await prisma.relay.findMany({
        orderBy: { priority: 'asc' },
      });
      res.json(relays);
    } catch (err) {
      console.error('List relays error:', err);
      res.status(500).json({ error: 'Internal server error' });
    }
  }
);

router.post(
  '/',
  requireAuth,
  requires('relays.manage'),
  async (req: Request, res: Response) => {
    try {
      const { url, priority } = req.body;
      if (!url) {
        res.status(400).json({ error: 'url is required' });
        return;
      }

      const relay = await prisma.relay.create({
        data: {
          url,
          priority: priority || 0,
        },
      });

      res.status(201).json(relay);
    } catch (err) {
      console.error('Create relay error:', err);
      res.status(500).json({ error: 'Internal server error' });
    }
  }
);

router.patch(
  '/:id',
  requireAuth,
  requires('relays.manage'),
  async (req: Request, res: Response) => {
    try {
      const relay = await prisma.relay.findUnique({
        where: { id: req.params.id as string },
      });
      if (!relay) {
        res.status(404).json({ error: 'Relay not found' });
        return;
      }

      const { url, priority, active } = req.body;
      const updateData: any = {};
      if (url !== undefined) updateData.url = url;
      if (priority !== undefined) updateData.priority = priority;
      if (active !== undefined) updateData.active = active;

      const updated = await prisma.relay.update({
        where: { id: req.params.id as string },
        data: updateData,
      });

      res.json(updated);
    } catch (err) {
      console.error('Update relay error:', err);
      res.status(500).json({ error: 'Internal server error' });
    }
  }
);

router.delete(
  '/:id',
  requireAuth,
  requires('relays.manage'),
  async (req: Request, res: Response) => {
    try {
      const relay = await prisma.relay.findUnique({
        where: { id: req.params.id as string },
      });
      if (!relay) {
        res.status(404).json({ error: 'Relay not found' });
        return;
      }

      await prisma.relay.delete({ where: { id: req.params.id as string } });
      res.json({ success: true });
    } catch (err) {
      console.error('Delete relay error:', err);
      res.status(500).json({ error: 'Internal server error' });
    }
  }
);

router.post(
  '/:id/test',
  requireAuth,
  requires('relays.manage'),
  async (req: Request, res: Response) => {
    try {
      const relay = await prisma.relay.findUnique({
        where: { id: req.params.id as string },
      });
      if (!relay) {
        res.status(404).json({ error: 'Relay not found' });
        return;
      }

      const pool = new SimplePool();
      const startTime = Date.now();

      try {
        await pool.get([relay.url], { kinds: [1], limit: 1 });
        const latency = Date.now() - startTime;
        res.json({ success: true, latency, url: relay.url });
      } catch {
        res.json({ success: false, error: 'Connection failed', url: relay.url });
      } finally {
        pool.close([relay.url]);
      }
    } catch (err) {
      console.error('Test relay error:', err);
      res.status(500).json({ error: 'Internal server error' });
    }
  }
);

export default router;
