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

router.get('/', (req, res) => {
  const db = getDb();
  const clients = db.prepare('SELECT id, name FROM clients ORDER BY name').all();
  const clientId = req.query.client_id || null;
  const saved = req.query.saved === '1';
  let client = null, assessments = [], prevAssessment = null;
  if (clientId) {
    client = db.prepare('SELECT * FROM clients WHERE id = ?').get(clientId);
    assessments = db.prepare('SELECT * FROM assessments WHERE client_id = ? ORDER BY created_at DESC LIMIT 10').all(clientId);
    if (assessments.length > 0) prevAssessment = assessments[0];
  }
  res.render('consultancy-framework', { clients, clientId, client, assessments, prevAssessment, saved, loadedAnswers: null, loadedReport: null });
});

router.post('/save', async (req, res) => {
  const db = getDb();
  const { client_id, answers, report } = req.body;
  if (!client_id) return res.status(400).json({ error: 'Client is required' });
  if (!answers) return res.status(400).json({ error: 'Answers required' });
  const answersJson = typeof answers === 'string' ? answers : JSON.stringify(answers);
  const reportJson = typeof report === 'string' ? report : JSON.stringify(report || {});
  const result = db.prepare('INSERT INTO assessments (client_id, answers, report) VALUES (?, ?, ?)').run(client_id, answersJson, reportJson);
  logAudit(req.session.userId, req.session.username, 'assessment_created', 'assessment', result.lastInsertRowid, 'Consultancy framework assessment');
  const client = db.prepare('SELECT * FROM clients WHERE id = ?').get(client_id);
  if (client && client.status === 'lead') {
    db.prepare("UPDATE clients SET status='active', updated_at=datetime('now') WHERE id=?").run(client_id);
  }
  res.json({ id: result.lastInsertRowid, redirect: '/consulting?client_id=' + client_id + '&saved=1' });
});

router.get('/report/:id', (req, res) => {
  const db = getDb();
  const assessment = db.prepare('SELECT a.*, c.name as client_name FROM assessments a LEFT JOIN clients c ON c.id = a.client_id WHERE a.id = ?').get(req.params.id);
  if (!assessment) return res.redirect('/consulting');
  try {
    const answers = JSON.parse(assessment.answers);
    const report = JSON.parse(assessment.report);
    const clients = db.prepare('SELECT id, name FROM clients ORDER BY name').all();
    res.render('consultancy-framework', { clients, clientId: assessment.client_id, client: { name: assessment.client_name }, assessments: [], prevAssessment: assessment, saved: false, loadedAnswers: answers, loadedReport: report });
  } catch(e) { res.redirect('/consulting?client_id=' + assessment.client_id); }
});

module.exports = router;
