const Certificate = require("../models/certificateModel");
const User = require("../models/User");
const Course = require("../models/Course");

// 1. Issue Certificate (Called when course is 100% complete)
exports.issueCertificate = async (req, res) => {
  try {
    const { userId, courseId } = req.body; // Or get userId from req.user.id

    // Check if already exists
    const existingCert = await Certificate.findOne({
      student: userId,
      course: courseId,
    });
    if (existingCert) {
      return res.status(200).json({ success: true, data: existingCert });
    }

    // Fetch details to snapshot
    const user = await User.findById(userId);
    const course = await Course.findById(courseId);

    if (!user || !course) throw new Error("User or Course not found");

    const newCert = await Certificate.create({
      student: userId,
      course: courseId,
      studentName: user.name,
      courseName: course.name,
      instructors: course.instructors.map((inst) => inst.name),
    });

    res.status(201).json({ success: true, data: newCert });
  } catch (err) {
    res.status(400).json({ success: false, message: err.message });
  }
};

// 2. Get Certificate Details (For viewing)
exports.getCertificate = async (req, res) => {
  try {
    // Can find by internal _id OR public certificateId
    const query = req.params.id.startsWith("CERT")
      ? { certificateId: req.params.id }
      : { _id: req.params.id };

    const cert = await Certificate.findOne(query)
      .populate("student", "name")
      .populate("course", "name");

    if (!cert)
      return res
        .status(404)
        .json({ success: false, message: "Certificate not found" });

    res.status(200).json({ success: true, data: cert });
  } catch (err) {
    res.status(500).json({ success: false, message: err.message });
  }
};
