const prisma = require("../lib/prisma");
const { notifyUser, notifyManyUsers } = require("../services/notification.service");

//student submit assignment
exports.submitAssignment = async (req, res) => {
  try {
    const studentId = req.user.id;
    const assignmentId = parseInt(req.params.assignmentId);
    if (!req.file) {
      return res.status(400).json({ message: "Submission file is required" });
    }
    const fileUrl = req.file.path;

    //check assignment exists
    const assignment = await prisma.assignment.findUnique({
      where: { id: assignmentId },
    });

    if (!assignment) {
      return res.status(404).json({ message: "Assignment not found" });
    }

    //prevent duplicate submission
    const already = await prisma.submission.findFirst({
      where: {
        assignmentId: assignmentId,
        studentId: req.user.id,
      },
    });
    if (already) {
      return res
        .status(400)
        .json({ message: "You have already submitted this assignment" });
    }

    //create submission
    const submission = await prisma.submission.create({
      data: {
        fileUrl,
        assignmentId: assignmentId,
        studentId: req.user.id,
        status: "submitted",
      },
      include: {
        assignment: true, // <-- include assignment relation
      },
    });

    await prisma.lessonProgress.upsert({
      where: {
        studentId_lessonId: {
          studentId,
          lessonId: submission.assignment.lessonId,
        },
      },
      update: { assignmentCompleted: true },
      create: {
        studentId,
        lessonId: submission.assignment.lessonId,
        assignmentCompleted: true,
      },
    });

     // 🔔 Notify the teacher
    if (assignment.teacherId) {
      const message = `Student "${req.user.firstName} ${req.user.lastName}" has submitted the assignment "${assignment.title}".`;
      await notifyUser(req, assignment.teacherId, message, null); // senderId = null for system
    }

    return res
      .status(200)
      .json({ message: "Assignment submitted successfully", submission });
  } catch (err) {
    console.log(err);
    return res.status(500).json({ message: "Server error" });
  }
};

//teacher gets submission
exports.getSubmissionByAssignment = async (req, res) => {
  try {
    const assignmentId = parseInt(req.params.assignmentId);

    const submissions = await prisma.submission.findMany({
      where: { assignmentId },
      include: {
        student: {
          select: {
            id: true,
            firstName: true,
            lastName: true,
            email: true,
          },
        },
      },
      orderBy: { submittedAt: "desc" },
    });
    return res.json(submissions);
  } catch (err) {
    console.log(err);
    return res.status(500).json({ message: "Server error" });
  }
};

//teacher grades submission
exports.gradeSubmission = async (req, res) => {
  try {
    const id = parseInt(req.params.id);
    const { marks, feedback } = req.body;

    const submission = await prisma.submission.update({
      where: { id },
      data: {
        marks: parseInt(marks),
        status: "graded",
        feedback: feedback || " ",
      },
       include: {
        student: true, // get student info
        assignment: true, // get assignment info (for title)
      },
    });

    // 🔔 Notify the student
    if (submission.studentId) {
      const message = `Your submission for "${submission.assignment.title}" has been graded. You received ${marks} marks.`;
      await notifyUser(req, submission.studentId, message, null); // senderId = null for system
    }

    return res.json({
      message: "Submission graded successfully",
      submission,
    });
  } catch (err) {
    console.log(err);
    return res.status(500).json("Server error");
  }
};

//delete submission
exports.deleteSubmission = async (req, res) => {
  try {
    const id = parseInt(req.params.id);
    await prisma.submission.delete({
      where: { id },
    });
  } catch (err) {
    console.log(err);
    return res.status(500).json({ message: "Server error" });
  }
};

// get single submission by id (teacher/admin)
exports.getSubmissionById = async (req, res) => {
  try {
    const id = parseInt(req.params.id);

    const submission = await prisma.submission.findUnique({
      where: { id },
      include: {
        student: {
          select: {
            id: true,
            firstName: true,
            lastName: true,
            email: true,
          },
        },
        assignment: {
          include: {
            lesson: {
              include: {
                subject: true,
              },
            },
          },
        },
      },
    });

    if (!submission) {
      return res.status(404).json({ message: "Submission not found" });
    }

    return res.json(submission);
  } catch (err) {
    console.error(err);
    return res.status(500).json({ message: "Server error" });
  }
};

exports.getStudentSubmissions = async (req, res) => {
  try {
    const user = req.user; // comes from authMiddleware

    if (user.role !== "student") {
      return res.status(403).json({ message: "Unauthorized" });
    }

    // Check enrolled subjects
    const enrollments = await prisma.enrollment.findMany({
      where: { studentId: user.id },
      select: { subjectId: true },
    });

    const enrolledSubjectIds = enrollments.map((e) => e.subjectId);

    if (!enrolledSubjectIds.length) {
      return res
        .status(403)
        .json({ message: "You are not enrolled in any subjects" });
    }

    // Pagination params
    const page = parseInt(req.query.page) || 1;
    const pageSize = parseInt(req.query.pageSize) || 10;
    const skip = (page - 1) * pageSize;

    // Fetch total count
    const total = await prisma.submission.count({
      where: {
        studentId: user.id,
        assignment: {
          lesson: { subjectId: { in: enrolledSubjectIds } },
        },
      },
    });

    // Fetch submissions with pagination
    const submissions = await prisma.submission.findMany({
      where: {
        studentId: user.id,
        assignment: {
          lesson: { subjectId: { in: enrolledSubjectIds } },
        },
      },
      include: {
        assignment: { include: { lesson: { include: { subject: true } } } },
      },
      orderBy: { submittedAt: "desc" },
      skip,
      take: pageSize,
    });

    return res.json({ submissions, total });
  } catch (err) {
    console.error(err);
    return res.status(500).json({ message: "Server Error" });
  }
};
