const prisma = require("../lib/prisma");

/**
 * ADMIN: Create Demo Class
 */
const createDemo = async (req, res) => {
  try {
    const {
      title,
      description,
      demoDate,
      subjectId,
      teacherId,
      meetingUrl,
    } = req.body;

    const demo = await prisma.demoClass.create({
      data: {
        title,
        description,
        demoDate: new Date(demoDate),
        subjectId: Number(subjectId),
        teacherId: Number(teacherId),
        meetingUrl,
        createdById: req.user.id, // admin
      },
    });

    res.status(201).json(demo);
  } catch (err) {
    console.error(err);
    res.status(500).json({
      message: "Failed to create demo",
      error: err.message,
    });
  }
};

/**
 * ADMIN: List All Demos
 */
const getAllDemos = async (req, res) => {
  try {
    const demos = await prisma.demoClass.findMany({
      include: {
        subject: { select: { title: true, thumbnailUrl: true, } },
        teacher: { select: { firstName: true, lastName: true } },
      },
      orderBy: { createdAt: "desc" },
    });

    res.json(demos);
  } catch (err) {
    res.status(500).json({ message: "Failed to fetch demos" });
  }
};

/**
 * PUBLIC: List Public Demos
 */
const getPublicDemos = async (req, res) => {
  try {
    const demos = await prisma.demoClass.findMany({
      where: { isPublic: true },
      include: {
        subject: { select: { title: true, thumbnailUrl: true, } },
        teacher: { select: { firstName: true, lastName: true } },
      },
      orderBy: { demoDate: "asc" },
    });

    res.json(demos);
  } catch (err) {
    res.status(500).json({ message: "Failed to fetch public demos" });
  }
};

/**
 * TEACHER: List Own Demos
 */
const getTeacherDemos = async (req, res) => {
  try {
    const demos = await prisma.demoClass.findMany({
      where: { teacherId: req.user.id },
      include: {
        subject: { select: { title: true, thumbnailUrl: true, } },
        teacher: { select: { firstName: true, lastName: true } },
      },
    });

    res.json(demos);
  } catch (err) {
    res.status(500).json({ message: "Failed to fetch teacher demos" });
  }
};

/**
 * ADMIN: End Demo Class
 */
const endDemo = async (req, res) => {
  try {
    const { id } = req.params;

    const demo = await prisma.demoClass.update({
      where: { id: Number(id) },
      data: { endedAt: new Date() },
    });

    res.json(demo);
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: "Failed to end demo", error: err.message });
  }
};


module.exports = {
  createDemo,
  getAllDemos,
  getPublicDemos,
  getTeacherDemos,
  endDemo
};
