/**
 * Class Room / Course Scheme/Plan controller (P1-UX-7).
 *
 * Implements the Lesson-unit-facing slice of UI/UX feedback PDF §9
 * ("Academic Structure (Course Scheme/Plan)"). The page on the client
 * composes three sub-tabs:
 *
 *   - Learning Material — every lesson plan for the teacher's subjects,
 *     with a "Virtual Class Room" button on any row whose
 *     lesson_plans.meet_url or .classroom_url is set (PDF §3 + §9).
 *   - Export Scheme       — placeholder; exports the scheme as CSV/PDF.
 *   - Learner              — per-learner progress within that subject
 *     (placeholder summary; full integration deferred).
 *
 * The endpoint here covers only what's needed to render the page: a
 * filtered list of lesson plans for the caller. Authoring / editing
 * still happens through /api/teacher/lesson-plans and is unchanged.
 */

const express = require('express');
const router = express.Router();
const path = require('path');
const Database = require('better-sqlite3');

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

// Auth middleware — same shape every controller in this repo uses.
// Inline because controllers don't share it; promoting to requireRole
// is part of P1-10's sweep but not yet applied here.
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 { jwtSecret: JWT_SECRET } = require('../config');
    req.user = jwt.verify(token, JWT_SECRET);
    next();
  } catch (err) {
    res.status(401).json({ error: 'Invalid token' });
  }
};

/**
 * GET /api/class-room
 *
 * Returns an aggregated payload the UI can render without further
 * joining:
 *   {
 *     lesson_plans: [...],          // every row the caller is allowed to see
 *     total: <number>,
 *     with_live_link: <number>,     // rows that have meet_url OR classroom_url
 *     upcoming: <number>            // rows with date >= today
 *   }
 *
 * Visibility: every authenticated user can call /class-room. Privileged
 * users (admin/principal) see every row in the school. Teachers see
 * rows they authored. Students / parents get a future-PR scope (today
 * they get an empty list with a "no access" note).
 */
router.get('/', auth, (req, res) => {
  try {
    const role = req.user.role;
    let rows;
    if (['school_admin', 'systems_admin', 'principal'].includes(role)) {
      rows = db.prepare(`
        SELECT lp.id, lp.uid, lp.teacher_id, lp.subject_id, lp.date,
               lp.topic, lp.status,
               lp.meet_url, lp.classroom_url,
               sub.name AS subject_name, sub.code AS subject_code,
               u.first_name || ' ' || u.last_name AS teacher_name
        FROM lesson_plans lp
        JOIN subjects sub ON lp.subject_id = sub.id
        JOIN users u ON lp.teacher_id = u.id
        WHERE lp.is_deleted = 0
        ORDER BY COALESCE(lp.date, '') DESC, lp.created_at DESC
      `).all();
    } else if (role === 'teacher') {
      rows = db.prepare(`
        SELECT lp.id, lp.uid, lp.teacher_id, lp.subject_id, lp.date,
               lp.topic, lp.status,
               lp.meet_url, lp.classroom_url,
               sub.name AS subject_name, sub.code AS subject_code,
               u.first_name || ' ' || u.last_name AS teacher_name
        FROM lesson_plans lp
        JOIN subjects sub ON lp.subject_id = sub.id
        JOIN users u ON lp.teacher_id = u.id
        WHERE lp.teacher_id = ? AND lp.is_deleted = 0
        ORDER BY COALESCE(lp.date, '') DESC, lp.created_at DESC
      `).all(req.user.id);
    } else {
      // Student / parent / other roles — gate for now; the student-side
      // "Join Class" surface lands in a follow-up PR.
      return res.json({
        lesson_plans: [],
        total: 0,
        with_live_link: 0,
        upcoming: 0,
        note: 'Student / parent scope is not yet exposed in this slice.',
      });
    }

    const today = new Date().toISOString().slice(0, 10);
    const withLink = rows.filter((r) => r.meet_url || r.classroom_url).length;
    const upcoming = rows.filter((r) => r.date && r.date >= today).length;

    res.json({
      lesson_plans: rows,
      total: rows.length,
      with_live_link: withLink,
      upcoming,
    });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

module.exports = router;
