import { Router } from 'express';
import db from '../db.js';
import { parseSubscriptionContent } from '../parsers/index.js';

const router = Router();

// GET /api/subscriptions
router.get('/', (_req, res) => {
  const rows = db.prepare('SELECT * FROM subscriptions ORDER BY id').all();
  res.json(rows);
});

// POST /api/subscriptions
router.post('/', (req, res) => {
  const { name, url } = req.body;
  if (!name || !url) {
    return res.status(400).json({ error: 'name and url are required' });
  }
  const result = db.prepare('INSERT INTO subscriptions (name, url) VALUES (?, ?)').run(name, url);
  res.json({ id: result.lastInsertRowid });
});

// PUT /api/subscriptions/:id
router.put('/:id', (req, res) => {
  const { id } = req.params;
  const { name, url, enabled } = req.body;
  const sub = db.prepare('SELECT * FROM subscriptions WHERE id = ?').get(id);
  if (!sub) return res.status(404).json({ error: 'not found' });

  db.prepare('UPDATE subscriptions SET name = ?, url = ?, enabled = ? WHERE id = ?')
    .run(name ?? (sub as any).name, url ?? (sub as any).url, enabled ?? (sub as any).enabled, id);
  res.json({ ok: true });
});

// DELETE /api/subscriptions/:id
router.delete('/:id', (req, res) => {
  const { id } = req.params;
  db.prepare('DELETE FROM subscriptions WHERE id = ?').run(id);
  res.json({ ok: true });
});

// POST /api/subscriptions/:id/fetch - trigger fetch and parse
router.post('/:id/fetch', async (req, res) => {
  const { id } = req.params;
  const sub = db.prepare('SELECT * FROM subscriptions WHERE id = ?').get(id) as any;
  if (!sub) return res.status(404).json({ error: 'not found' });

  try {
    const response = await fetch(sub.url);
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    const rawConfig = await response.text();

    // Save existing enabled states by node name
    const existingNodes = db.prepare('SELECT name, enabled FROM fetched_nodes WHERE subscription_id = ?').all(id) as any[];
    const enabledMap = new Map(existingNodes.map((n: any) => [n.name, n.enabled]));

    // Parse nodes
    const nodes = parseSubscriptionContent(rawConfig);

    // Replace nodes in transaction
    const replace = db.transaction(() => {
      db.prepare('DELETE FROM fetched_nodes WHERE subscription_id = ?').run(id);
      const insert = db.prepare(
        'INSERT INTO fetched_nodes (subscription_id, name, type, server, port, surge_line, enabled) VALUES (?, ?, ?, ?, ?, ?, ?)'
      );
      for (const node of nodes) {
        const enabled = enabledMap.get(node.name) ?? 1;
        insert.run(id, node.name, node.type, node.server, node.port, node.surgeLine, enabled);
      }
      db.prepare('UPDATE subscriptions SET raw_config = ?, last_fetch = ?, node_count = ? WHERE id = ?')
        .run(rawConfig, new Date().toISOString(), nodes.length, id);
    });
    replace();

    res.json({ nodeCount: nodes.length });
  } catch (err: any) {
    res.status(502).json({ error: err.message });
  }
});

// GET /api/subscriptions/:id/nodes
router.get('/:id/nodes', (req, res) => {
  const { id } = req.params;
  const nodes = db.prepare('SELECT * FROM fetched_nodes WHERE subscription_id = ? ORDER BY id').all(id);
  res.json(nodes);
});

export default router;
