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

router.get('/', (req, res) => {
  const db = getDb();
  const tasks = db.prepare(`
    SELECT t.*, e.title as engagement_title, c.name as client_name
    FROM tasks t
    JOIN engagements e ON e.id = t.engagement_id
    JOIN clients c ON c.id = e.client_id
    ORDER BY
      CASE t.priority WHEN 'critical' THEN 0 WHEN 'high' THEN 1 WHEN 'medium' THEN 2 WHEN 'low' THEN 3 END,
      t.due_date ASC
  `).all();
  res.render('task-list', { tasks });
});

router.post('/new', (req, res) => {
  const db = getDb();
  const { engagement_id, title, description, priority, due_date } = req.body;
  if (!title || !title.trim()) return res.redirect('back');
  db.prepare('INSERT INTO tasks (engagement_id, title, description, priority, due_date) VALUES (?, ?, ?, ?, ?)')
    .run(engagement_id, title, description, priority || 'medium', due_date);
  res.redirect('back');
});

router.post('/:id/status', (req, res) => {
  const db = getDb();
  db.prepare("UPDATE tasks SET status=?, updated_at=datetime('now') WHERE id=?")
    .run(req.body.status, req.params.id);
  res.redirect('back');
});

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

module.exports = router;
