'use strict';

const installV34LaunchRoutes = require('./v34-launch-routes');

function userId(req) {
  return Number(req.user?.id || req.user?.user_id || req.user?.parent_id || 0);
}

function cleanText(value, max, fallback = '') {
  return String(value ?? fallback).trim().slice(0, max);
}

async function requireParent(req, res, pool) {
  const id = userId(req);
  if (!Number.isInteger(id) || id <= 0) {
    res.status(403).json({ error: 'A verified parent/teacher account is required' });
    return null;
  }
  const role = String(req.user?.role || req.user?.type || req.user?.user_type || '').toLowerCase();
  if (role === 'student') {
    res.status(403).json({ error: 'Student accounts cannot access teacher records' });
    return null;
  }
  const links = await pool.query('SELECT 1 FROM parent_student_links WHERE parent_user_id=$1 LIMIT 1', [id]);
  if (!links.rowCount) {
    res.status(403).json({ error: 'This parent account has no verified student ownership links' });
    return null;
  }
  return id;
}

module.exports = function installV35BackendTestRoutes(app, pool, authenticateToken) {
  if (!app || !pool) throw new Error('V35 routes require the Express app and PostgreSQL pool.');
  if (typeof authenticateToken !== 'function') throw new Error('V35 routes require the existing authenticateToken middleware.');
  installV34LaunchRoutes(app, pool, authenticateToken);
  const protect = authenticateToken;

  app.get('/api/v35/status', protect, async (req, res) => {
    try {
      const result = await pool.query(`SELECT
        to_regclass('public.parent_student_links') IS NOT NULL AS ownership_ready,
        to_regclass('public.teacher_profiles') IS NOT NULL AS profiles_ready,
        to_regclass('public.curriculum_submissions') IS NOT NULL AS submissions_ready,
        to_regclass('public.student_activity_sessions') IS NOT NULL AS activity_ready,
        to_regclass('public.student_menu_controls') IS NOT NULL AS menu_ready,
        EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='public' AND table_name='curriculum_submissions' AND column_name='writing_score') AS writing_ready`);
      const row = result.rows[0] || {};
      res.json({ version:'V35', ready:Object.values(row).every(Boolean), ...row });
    } catch (error) {
      console.error('V35 status failed:', error);
      res.status(500).json({ error:'V35 database readiness check failed' });
    }
  });

  app.get('/api/teacher/profile', protect, async (req, res) => {
    try {
      const parentId = await requireParent(req, res, pool);
      if (!parentId) return;
      const result = await pool.query('SELECT display_name, title, avatar_data, timezone, preferences, updated_at FROM teacher_profiles WHERE parent_user_id=$1', [parentId]);
      res.json(result.rows[0] || { display_name:'', title:'Parent / Teacher', avatar_data:'', timezone:'America/Los_Angeles', preferences:{} });
    } catch (error) {
      console.error('Teacher profile load failed:', error);
      res.status(500).json({ error:'Unable to load teacher profile' });
    }
  });

  app.put('/api/teacher/profile', protect, async (req, res) => {
    try {
      const parentId = await requireParent(req, res, pool);
      if (!parentId) return;
      const avatar = cleanText(req.body?.avatar_data || req.body?.avatar || '', 1500000);
      if (avatar && !/^data:image\/(?:png|jpeg|jpg|webp|gif);base64,/i.test(avatar)) return res.status(400).json({ error:'Profile image must be an uploaded image' });
      const timezone = cleanText(req.body?.timezone, 80, 'America/Los_Angeles');
      const preferences = req.body?.preferences && typeof req.body.preferences === 'object' && !Array.isArray(req.body.preferences) ? req.body.preferences : {};
      const result = await pool.query(
        `INSERT INTO teacher_profiles (parent_user_id, display_name, title, avatar_data, timezone, preferences, updated_at)
         VALUES ($1,$2,$3,$4,$5,$6::jsonb,NOW())
         ON CONFLICT (parent_user_id) DO UPDATE SET display_name=EXCLUDED.display_name, title=EXCLUDED.title,
           avatar_data=EXCLUDED.avatar_data, timezone=EXCLUDED.timezone, preferences=EXCLUDED.preferences, updated_at=NOW()
         RETURNING display_name, title, avatar_data, timezone, preferences, updated_at`,
        [parentId, cleanText(req.body?.display_name, 160), cleanText(req.body?.title, 120, 'Parent / Teacher'), avatar, timezone, JSON.stringify(preferences)]
      );
      res.json(result.rows[0]);
    } catch (error) {
      console.error('Teacher profile save failed:', error);
      res.status(500).json({ error:'Unable to save teacher profile' });
    }
  });

  app.get('/api/teacher/dashboard', protect, async (req, res) => {
    try {
      const parentId = await requireParent(req, res, pool);
      if (!parentId) return;
      const result = await pool.query(
        `WITH owned AS (
           SELECT s.* FROM students s JOIN parent_student_links l ON l.student_id=s.id
           WHERE l.parent_user_id=$1 AND lower(COALESCE(s.status,'active')) <> 'inactive'
         ), activity AS (
           SELECT student_id,
             MIN(started_at) FILTER (WHERE (started_at AT TIME ZONE 'America/Los_Angeles')::date=(NOW() AT TIME ZONE 'America/Los_Angeles')::date) AS first_login,
             MAX(last_activity_at) AS last_activity,
             BOOL_OR(ended_at IS NULL AND last_activity_at >= NOW()-INTERVAL '90 seconds') AS working_now,
             COALESCE(SUM(GREATEST(0,EXTRACT(EPOCH FROM (COALESCE(ended_at,last_activity_at)-started_at)))) FILTER (WHERE (started_at AT TIME ZONE 'America/Los_Angeles')::date=(NOW() AT TIME ZONE 'America/Los_Angeles')::date),0)::integer AS seconds_today,
             (ARRAY_AGG(COALESCE(assignment_title,subject,note) ORDER BY last_activity_at DESC))[1] AS current_activity
           FROM student_activity_sessions GROUP BY student_id
         ), work AS (
           SELECT student_id,
             COUNT(*) FILTER (WHERE (submitted_at AT TIME ZONE 'America/Los_Angeles')::date=(NOW() AT TIME ZONE 'America/Los_Angeles')::date) AS completed_today,
             ROUND(AVG(percentage) FILTER (WHERE percentage IS NOT NULL)) AS average,
             BOOL_OR(concern_flag) AS needs_attention,
             (ARRAY_AGG(concern_reason ORDER BY submitted_at DESC) FILTER (WHERE concern_flag))[1] AS concern_reason
           FROM curriculum_submissions GROUP BY student_id
         )
         SELECT o.id, o.first_name, o.last_name, o.grade_level, o.school_id, o.status,
                a.first_login, a.last_activity, COALESCE(a.working_now,FALSE) AS working_now,
                COALESCE(a.seconds_today,0) AS seconds_today, a.current_activity,
                COALESCE(w.completed_today,0)::integer AS completed_today, w.average,
                COALESCE(w.needs_attention,FALSE) AS needs_attention, COALESCE(w.concern_reason,'') AS concern_reason
         FROM owned o LEFT JOIN activity a ON a.student_id=o.id LEFT JOIN work w ON w.student_id=o.id
         ORDER BY o.first_name, o.last_name, o.id`,
        [parentId]
      );
      const students = result.rows;
      res.json({
        students,
        summary:{
          total_students:students.length,
          logged_in_today:students.filter(row => row.first_login).length,
          working_now:students.filter(row => row.working_now).length,
          completed_today:students.reduce((sum,row) => sum + Number(row.completed_today || 0),0),
          needs_attention:students.filter(row => row.needs_attention).length
        },
        generated_at:new Date().toISOString(),
        timezone:'America/Los_Angeles'
      });
    } catch (error) {
      console.error('Teacher dashboard load failed:', error);
      res.status(500).json({ error:'Unable to load teacher dashboard' });
    }
  });
};
