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

const router = Router();

/** Replace the node name prefix in a surge_line like "OldName = ss, ..." → "NewName = ss, ..." */
function renameSurgeLine(surgeLine: string, oldName: string, newName: string): string {
  if (surgeLine.startsWith(oldName + ' = ')) {
    return newName + surgeLine.slice(oldName.length);
  }
  return surgeLine;
}

// --- Fetched nodes ---

// PUT /api/nodes/fetched/batch — MUST be before /fetched/:id
router.put('/fetched/batch', (req, res) => {
  const { ids, enabled } = req.body;
  if (!Array.isArray(ids)) return res.status(400).json({ error: 'ids must be array' });
  const stmt = db.prepare('UPDATE fetched_nodes SET enabled = ? WHERE id = ?');
  const batch = db.transaction(() => {
    for (const id of ids) {
      stmt.run(enabled ? 1 : 0, id);
    }
  });
  batch();
  res.json({ ok: true });
});

// PUT /api/nodes/fetched/:id - toggle enabled
router.put('/fetched/:id', (req, res) => {
  const { id } = req.params;
  const { enabled } = req.body;
  db.prepare('UPDATE fetched_nodes SET enabled = ? WHERE id = ?').run(enabled ? 1 : 0, id);
  res.json({ ok: true });
});

// --- Static nodes ---

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

// POST /api/nodes/static
router.post('/static', (req, res) => {
  const { uri, name: customName } = req.body;
  if (!uri) return res.status(400).json({ error: 'uri is required' });

  const node = parseNodeUri(uri);
  if (!node) return res.status(400).json({ error: 'unsupported or invalid URI' });

  // Allow custom name override
  const finalName = customName?.trim() || node.name;
  const surgeLine = renameSurgeLine(node.surgeLine, node.name, finalName);

  const maxOrder = db.prepare('SELECT MAX(sort_order) as m FROM static_nodes').get() as any;
  const sortOrder = (maxOrder?.m ?? -1) + 1;

  const result = db.prepare(
    'INSERT INTO static_nodes (name, uri, type, surge_line, sort_order) VALUES (?, ?, ?, ?, ?)'
  ).run(finalName, uri, node.type, surgeLine, sortOrder);

  res.json({ id: result.lastInsertRowid, name: finalName, type: node.type, server: node.server, port: node.port, surgeLine });
});

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

  const newName = name ?? node.name;
  const newEnabled = enabled ?? node.enabled;
  const newSortOrder = sort_order ?? node.sort_order;

  // If name changed, update surge_line too
  let newSurgeLine = node.surge_line;
  if (name && name !== node.name) {
    newSurgeLine = renameSurgeLine(node.surge_line, node.name, name);
  }

  db.prepare('UPDATE static_nodes SET name = ?, surge_line = ?, enabled = ?, sort_order = ? WHERE id = ?')
    .run(newName, newSurgeLine, newEnabled, newSortOrder, id);
  res.json({ ok: true });
});

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

export default router;
