/**
 * Social Controller
 * Handles student social documents
 */

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) => {
  if (req.user.role !== 'teacher' && req.user.role !== 'admin') {
    return res.status(403).json({ error: 'Teacher or Admin access required' });
  }
  next();
};

// ============ STUDENT SOCIAL DOCUMENTS ============

router.get('/student-docs/:student_uid', auth, teacherOnly, (req, res) => {
  const doc = db.prepare(`
    SELECT sd.*, u.first_name, u.last_name
    FROM student_social_docs sd
    JOIN users u ON sd.student_id = u.id
    WHERE u.uid = ? AND sd.is_deleted = 0
  `).get(req.params.student_uid);
  res.json(doc || { message: 'No social document found for this student' });
});

router.post('/student-docs', auth, teacherOnly, (req, res) => {
  const { student_id, learner_type, past_behavior, family_size, parents_available, home_environment, medical_notes, social_strengths, social_challenges, interests, other_data } = req.body;
  
  // Check if it already exists
  const existing = db.prepare('SELECT id FROM student_social_docs WHERE student_id = ? AND is_deleted = 0').get(student_id);
  
  if (existing) {
    db.prepare(`
      UPDATE student_social_docs
      SET learner_type = ?, past_behavior = ?, family_size = ?, parents_available = ?, home_environment = ?, medical_notes = ?, social_strengths = ?, social_challenges = ?, interests = ?, other_data = ?, updated_by = ?, updated_at = CURRENT_TIMESTAMP, sync_status = 'pending'
      WHERE id = ?
    `).run(learner_type, past_behavior, family_size, parents_available, home_environment, medical_notes, social_strengths, social_challenges, interests, other_data, req.user.id, existing.id);
    return res.json({ success: true, message: 'Document updated' });
  }

  const uid = uuidv4();
  const result = db.prepare(`
    INSERT INTO student_social_docs (uid, student_id, learner_type, past_behavior, family_size, parents_available, home_environment, medical_notes, social_strengths, social_challenges, interests, other_data, updated_by, sync_status)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending')
  `).run(uid, student_id, learner_type, past_behavior, family_size, parents_available, home_environment, medical_notes, social_strengths, social_challenges, interests, other_data, req.user.id);
  res.json({ id: result.lastInsertRowid, uid });
});

module.exports = router;
