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

const router = Router();

router.get(
  '/',
  requireAuth,
  async (req: Request, res: Response) => {
    try {
      const relays = await prisma.userRelay.findMany({
        where: { pubkey: req.user!.pubkey },
        orderBy: { createdAt: 'asc' },
      });
      res.json(relays);
    } catch (err) {
      console.error('List user relays error:', err);
      res.status(500).json({ error: 'Internal server error' });
    }
  }
);

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

      const normalized = url.trim().replace(/\/+$/, '');
      if (!normalized.startsWith('wss://') && !normalized.startsWith('ws://')) {
        res.status(400).json({ error: 'Relay URL must start with wss:// or ws://' });
        return;
      }

      const relay = await prisma.userRelay.upsert({
        where: {
          pubkey_url: { pubkey: req.user!.pubkey, url: normalized },
        },
        update: {
          read: read !== undefined ? read : true,
          write: write !== undefined ? write : true,
        },
        create: {
          pubkey: req.user!.pubkey,
          url: normalized,
          read: read !== undefined ? read : true,
          write: write !== undefined ? write : true,
        },
      });

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

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

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

router.post(
  '/import-nip65',
  requireAuth,
  async (req: Request, res: Response) => {
    try {
      const pubkey = req.user!.pubkey;
      const nip65 = await nostrService.fetchNip65Relays(pubkey);

      const allUrls = new Set<string>();
      const relayEntries: { url: string; read: boolean; write: boolean }[] = [];

      for (const url of nip65.write) {
        if (allUrls.has(url)) continue;
        allUrls.add(url);
        relayEntries.push({
          url,
          read: nip65.read.includes(url),
          write: true,
        });
      }
      for (const url of nip65.read) {
        if (allUrls.has(url)) continue;
        allUrls.add(url);
        relayEntries.push({ url, read: true, write: false });
      }

      if (relayEntries.length === 0) {
        res.json({ imported: 0, message: 'No NIP-65 relay list found for your pubkey' });
        return;
      }

      let imported = 0;
      for (const entry of relayEntries) {
        await prisma.userRelay.upsert({
          where: { pubkey_url: { pubkey, url: entry.url } },
          update: { read: entry.read, write: entry.write },
          create: { pubkey, url: entry.url, read: entry.read, write: entry.write },
        });
        imported++;
      }

      res.json({ imported, total: relayEntries.length });
    } catch (err) {
      console.error('Import NIP-65 error:', err);
      res.status(500).json({ error: 'Internal server error' });
    }
  }
);

export default router;
