/**
 * Teacher Controller
 * Handles syllabuses, schemes of work, focus points, and lesson plans
 */

const express = require('express');
const router = express.Router();
const path = require('path');
const Database = require('better-sqlite3');
const { v4: uuidv4 } = require('uuid');

const dbPath = process.env.DB_PATH || path.join(__dirname, '../../data/school.db');
const db = new Database(dbPath);
db.pragma('foreign_keys = ON');

// Auth middleware
const auth = (req, res, next) => {
  const token = req.headers.authorization?.split(' ')[1];
  if (!token) return res.status(401).json({ error: 'No token provided' });
  try {
    const jwt = require('jsonwebtoken');
    const JWT_SECRET = process.env.JWT_SECRET || 'africa-alert-secret-key-2024';
    req.user = jwt.verify(token, JWT_SECRET);
    next();
  } catch (err) {
    res.status(401).json({ error: 'Invalid token' });
  }
};

const teacherOnly = (req, res, next) => {
  const allowedRoles = ['teacher', 'admin', 'principal'];
  if (!allowedRoles.includes(req.user.role)) {
    return res.status(403).json({ error: 'Teacher, Principal or Admin access required' });
  }
  next();
};

// Helper to check if user is a department head and return their department ID
const getDepartmentHeadId = (userId) => {
  const dept = db.prepare('SELECT id FROM departments WHERE head_teacher_id = ? AND is_deleted = 0').get(userId);
  return dept ? dept.id : null;
};

// ============ SYLLABUSES ============

router.get('/syllabuses', auth, (req, res) => {
  const syllabuses = db.prepare(`
    SELECT s.*, sub.name as subject_name 
    FROM syllabuses s
    JOIN subjects_new sub ON s.subject_id = sub.id
    WHERE s.is_deleted = 0
  `).all();
  res.json(syllabuses);
});

router.post('/syllabuses', auth, teacherOnly, (req, res) => {
  const { subject_id, title, description, file_path, version } = req.body;
  const uid = uuidv4();
  const result = db.prepare(`
    INSERT INTO syllabuses (uid, subject_id, title, description, file_path, version, created_by, sync_status)
    VALUES (?, ?, ?, ?, ?, ?, ?, 'pending')
  `).run(uid, subject_id, title, description, file_path, version, req.user.id);
  res.json({ id: result.lastInsertRowid, uid });
});

// ============ SCHEMES OF WORK ============

router.get('/schemes', auth, (req, res) => {
  const isPrivileged = ['admin', 'principal'].includes(req.user.role);
  const deptId = getDepartmentHeadId(req.user.id);
  
  let query, params;
  
  if (isPrivileged) {
    query = 'SELECT sow.*, sub.name as subject_name, u.first_name, u.last_name FROM schemes_of_work sow JOIN subjects_new sub ON sow.subject_id = sub.id JOIN users u ON sow.teacher_id = u.id WHERE sow.is_deleted = 0';
    params = [];
  } else if (deptId) {
    // Department head: see all schemes in their department
    query = `
      SELECT sow.*, sub.name as subject_name, u.first_name, u.last_name 
      FROM schemes_of_work sow 
      JOIN subjects_new sub ON sow.subject_id = sub.id 
      JOIN users u ON sow.teacher_id = u.id 
      WHERE (sub.department_id = ? OR sow.teacher_id = ?) AND sow.is_deleted = 0
    `;
    params = [deptId, req.user.id];
  } else {
    // Normal teacher: see only own schemes
    query = 'SELECT sow.*, sub.name as subject_name FROM schemes_of_work sow JOIN subjects_new sub ON sow.subject_id = sub.id WHERE sow.teacher_id = ? AND sow.is_deleted = 0';
    params = [req.user.id];
  }
  
  const schemes = db.prepare(query).all(...params);
  res.json(schemes);
});

router.post('/schemes', auth, teacherOnly, (req, res) => {
  const { subject_id, term, academic_year, content } = req.body;
  const uid = uuidv4();
  const result = db.prepare(`
    INSERT INTO schemes_of_work (uid, subject_id, teacher_id, term, academic_year, content, sync_status)
    VALUES (?, ?, ?, ?, ?, ?, 'pending')
  `).run(uid, subject_id, req.user.id, term, academic_year, content);
  res.json({ id: result.lastInsertRowid, uid });
});

// ============ FOCUS POINTS ============

router.get('/focus-points', auth, (req, res) => {
  const { scheme_id } = req.query;
  const query = scheme_id 
    ? 'SELECT * FROM focus_points WHERE scheme_id = ? AND is_deleted = 0'
    : 'SELECT * FROM focus_points WHERE is_deleted = 0';
  const params = scheme_id ? [scheme_id] : [];
  const points = db.prepare(query).all(...params);
  res.json(points);
});

router.post('/focus-points', auth, teacherOnly, (req, res) => {
  const { scheme_id, topic, objectives, key_concepts, resources_needed } = req.body;
  const uid = uuidv4();
  const result = db.prepare(`
    INSERT INTO focus_points (uid, scheme_id, topic, objectives, key_concepts, resources_needed, sync_status)
    VALUES (?, ?, ?, ?, ?, ?, 'pending')
  `).run(uid, scheme_id, topic, objectives, key_concepts, resources_needed);
  res.json({ id: result.lastInsertRowid, uid });
});

// ============ LESSON PLANS ============

router.get('/lesson-plans', auth, (req, res) => {
  const isPrivileged = ['admin', 'principal'].includes(req.user.role);
  const deptId = getDepartmentHeadId(req.user.id);
  
  let query, params;

  if (isPrivileged) {
    query = 'SELECT lp.*, sub.name as subject_name, u.first_name, u.last_name FROM lesson_plans lp JOIN subjects_new sub ON lp.subject_id = sub.id JOIN users u ON lp.teacher_id = u.id WHERE lp.is_deleted = 0';
    params = [];
  } else if (deptId) {
    query = `
      SELECT lp.*, sub.name as subject_name, u.first_name, u.last_name 
      FROM lesson_plans lp 
      JOIN subjects_new sub ON lp.subject_id = sub.id 
      JOIN users u ON lp.teacher_id = u.id 
      WHERE (sub.department_id = ? OR lp.teacher_id = ?) AND lp.is_deleted = 0
    `;
    params = [deptId, req.user.id];
  } else {
    query = 'SELECT lp.*, sub.name as subject_name FROM lesson_plans lp JOIN subjects_new sub ON lp.subject_id = sub.id WHERE lp.teacher_id = ? AND lp.is_deleted = 0';
    params = [req.user.id];
  }
  
  const plans = db.prepare(query).all(...params);
  res.json(plans);
});

router.post('/lesson-plans', auth, teacherOnly, (req, res) => {
  const { subject_id, scheme_id, focus_point_id, date, topic, objectives, introduction, development, conclusion, assessment_method, homework, reflections } = req.body;
  const uid = uuidv4();
  const result = db.prepare(`
    INSERT INTO lesson_plans (uid, teacher_id, subject_id, scheme_id, focus_point_id, date, topic, objectives, introduction, development, conclusion, assessment_method, homework, reflections, sync_status)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending')
  `).run(uid, req.user.id, subject_id, scheme_id, focus_point_id, date, topic, objectives, introduction, development, conclusion, assessment_method, homework, reflections);
  res.json({ id: result.lastInsertRowid, uid });
});

module.exports = router;
