const express = require('express');
const router = express.Router();
const { getDb } = require('../db');

router.get('/', (req, res) => {
  const db = getDb();
  const devices = db.prepare(`
    SELECT nd.*, c.name as client_name
    FROM network_devices nd JOIN clients c ON c.id = nd.client_id
    ORDER BY nd.updated_at DESC
  `).all();
  const connections = db.prepare(`
    SELECT nc.*, c.name as client_name
    FROM network_connections nc JOIN clients c ON c.id = nc.client_id
    ORDER BY nc.created_at DESC
  `).all();
  res.render('networking-list', { devices, connections });
});

router.get('/devices/new', (req, res) => {
  const db = getDb();
  const clients = db.prepare('SELECT id, name FROM clients ORDER BY name').all();
  res.render('net-device-form', { device: null, clients, error: null });
});

router.post('/devices/new', (req, res) => {
  const db = getDb();
  const { client_id, name, device_type, model, manufacturer, ip_address, mgmt_ip, ports_count, os_version, notes, status } = req.body;
  if (!name || !client_id) return res.redirect('/networking');
  db.prepare('INSERT INTO network_devices (client_id, name, device_type, model, manufacturer, ip_address, mgmt_ip, ports_count, os_version, notes, status) VALUES (?,?,?,?,?,?,?,?,?,?,?)')
    .run(client_id, name, device_type, model, manufacturer, ip_address, mgmt_ip, ports_count || 24, os_version, notes, status || 'active');
  res.redirect('/networking');
});

router.get('/devices/:id', (req, res) => {
  const db = getDb();
  const device = db.prepare('SELECT nd.*, c.name as client_name FROM network_devices nd JOIN clients c ON c.id = nd.client_id WHERE nd.id = ?').get(req.params.id);
  if (!device) return res.redirect('/networking');
  const connections = db.prepare(`
    SELECT * FROM network_connections
    WHERE client_id = ? AND ((from_type = 'network_device' AND from_id = ?) OR (to_type = 'network_device' AND to_id = ?))
    ORDER BY created_at DESC
  `).all(device.client_id, req.params.id, req.params.id);
  res.render('net-device-detail', { device, connections });
});

router.get('/devices/:id/edit', (req, res) => {
  const db = getDb();
  const device = db.prepare('SELECT * FROM network_devices WHERE id = ?').get(req.params.id);
  if (!device) return res.redirect('/networking');
  const clients = db.prepare('SELECT id, name FROM clients ORDER BY name').all();
  res.render('net-device-form', { device, clients, error: null });
});

router.post('/devices/:id/edit', (req, res) => {
  const db = getDb();
  const { name, device_type, model, manufacturer, ip_address, mgmt_ip, ports_count, os_version, notes, status } = req.body;
  db.prepare("UPDATE network_devices SET name=?, device_type=?, model=?, manufacturer=?, ip_address=?, mgmt_ip=?, ports_count=?, os_version=?, notes=?, status=?, updated_at=datetime('now') WHERE id=?")
    .run(name, device_type, model, manufacturer, ip_address, mgmt_ip, ports_count, os_version, notes, status, req.params.id);
  res.redirect('/networking/devices/' + req.params.id);
});

router.post('/devices/:id/delete', (req, res) => {
  const db = getDb();
  db.prepare('DELETE FROM network_devices WHERE id = ?').run(req.params.id);
  res.redirect('/networking');
});

router.get('/connections/new', (req, res) => {
  const db = getDb();
  const clients = db.prepare('SELECT id, name FROM clients ORDER BY name').all();
  const netDevices = db.prepare('SELECT id, name, device_type FROM network_devices ORDER BY name').all();
  const rackDevices = db.prepare('SELECT rd.id, rd.name, rd.device_type, r.name as rack_name FROM rack_devices rd JOIN racks r ON r.id = rd.rack_id ORDER BY r.name, rd.position_u').all();
  res.render('net-connection-form', { connection: null, clients, netDevices, rackDevices, error: null });
});

router.post('/connections/new', (req, res) => {
  const db = getDb();
  const { client_id, name, from_type, from_id, from_port, to_type, to_id, to_port, media_type, speed, vlan, status, notes } = req.body;
  if (!client_id) return res.redirect('/networking');
  db.prepare('INSERT INTO network_connections (client_id, name, from_type, from_id, from_port, to_type, to_id, to_port, media_type, speed, vlan, status, notes) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)')
    .run(client_id, name, from_type, from_id || null, from_port, to_type, to_id || null, to_port, media_type || 'copper', speed || '1GbE', vlan, status || 'active', notes);
  res.redirect('/networking');
});

router.get('/connections/:id/edit', (req, res) => {
  const db = getDb();
  const connection = db.prepare('SELECT * FROM network_connections WHERE id = ?').get(req.params.id);
  if (!connection) return res.redirect('/networking');
  const clients = db.prepare('SELECT id, name FROM clients ORDER BY name').all();
  const netDevices = db.prepare('SELECT id, name, device_type FROM network_devices ORDER BY name').all();
  const rackDevices = db.prepare('SELECT rd.id, rd.name, rd.device_type, r.name as rack_name FROM rack_devices rd JOIN racks r ON r.id = rd.rack_id ORDER BY r.name, rd.position_u').all();
  res.render('net-connection-form', { connection, clients, netDevices, rackDevices, error: null });
});

router.post('/connections/:id/edit', (req, res) => {
  const db = getDb();
  const { name, from_type, from_id, from_port, to_type, to_id, to_port, media_type, speed, vlan, status, notes } = req.body;
  db.prepare('UPDATE network_connections SET name=?, from_type=?, from_id=?, from_port=?, to_type=?, to_id=?, to_port=?, media_type=?, speed=?, vlan=?, status=?, notes=? WHERE id=?')
    .run(name, from_type, from_id || null, from_port, to_type, to_id || null, to_port, media_type, speed, vlan, status, notes, req.params.id);
  res.redirect('/networking');
});

router.post('/connections/:id/delete', (req, res) => {
  const db = getDb();
  db.prepare('DELETE FROM network_connections WHERE id = ?').run(req.params.id);
  res.redirect('/networking');
});

module.exports = router;
