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

function sendSlack(webhookUrl, message) {
  return new Promise((resolve) => {
    if (!webhookUrl) return resolve(false);
    const data = JSON.stringify({ text: message });
    const url = new URL(webhookUrl);
    const client = url.protocol === 'https:' ? https : http;
    const req = client.request(webhookUrl, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(data) } }, (res) => {
      let body = '';
      res.on('data', c => body += c);
      res.on('end', () => resolve(true));
    });
    req.on('error', () => resolve(false));
    req.write(data);
    req.end();
  });
}

function createNotification(userId, type, title, message, channel) {
  const db = getDb();
  const result = db.prepare('INSERT INTO notifications (user_id, type, title, message, channel) VALUES (?,?,?,?,?)')
    .run(userId || null, type, title, message || '', channel || 'in-app');
  return result.lastInsertRowid;
}

async function sendNotification(userId, type, title, message) {
  const db = getDb();
  const nid = createNotification(userId, type, title, message, 'in-app');
  const settings = db.prepare('SELECT * FROM user_settings WHERE user_id = ?').get(userId);
  if (settings) {
    if (settings.slack_webhook && type !== 'test') {
      const user = db.prepare('SELECT username FROM users WHERE id = ?').get(userId);
      const msg = `[Mek-Tech] ${title}: ${message}`;
      sendSlack(settings.slack_webhook, msg).then(sent => {
        if (sent) db.prepare("UPDATE notifications SET sent=1, channel='slack' WHERE id=?").run(nid);
      });
    }
  }
  return nid;
}

router.get('/', (req, res) => {
  const db = getDb();
  const notifications = db.prepare('SELECT * FROM notifications WHERE user_id = ? OR user_id IS NULL ORDER BY created_at DESC LIMIT 100').all(req.session.userId);
  const unread = notifications.filter(n => !n.read).length;
  res.render('notification-list', { notifications, unread });
});

router.post('/:id/read', (req, res) => {
  const db = getDb();
  db.prepare("UPDATE notifications SET read=1 WHERE id=? AND (user_id=? OR user_id IS NULL)").run(req.params.id, req.session.userId);
  res.redirect('/notifications');
});

router.post('/read-all', (req, res) => {
  const db = getDb();
  db.prepare("UPDATE notifications SET read=1 WHERE user_id=? AND read=0").run(req.session.userId);
  res.redirect('/notifications');
});

router.get('/api/unread', (req, res) => {
  const db = getDb();
  const count = db.prepare("SELECT COUNT(*) as cnt FROM notifications WHERE (user_id=? OR user_id IS NULL) AND read=0").get(req.session.userId);
  res.json({ unread: count.cnt });
});

module.exports = { router, createNotification, sendNotification, sendSlack };
