console.log("ADMIN COURSE ROUTES LOADED");
const express = require("express");
const requireAdmin = require("../../middleware/requireAdmin");
const router = express.Router();
const Course = require("../../models/Course");

const multer = require("multer")
const path = require("path")

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, path.join(__dirname, "../../uploads"))
  },
  filename: (req, file, cb) => {
    const unique = Date.now() + "-" + Math.round(Math.random() * 1e9)
    cb(null, unique + path.extname(file.originalname))
  }
})

const upload = multer({ storage })

router.post("/courses", requireAdmin, upload.single("thumbnail"), async (req, res) => {
  try {
    const { name, slug, subject, price, description, class: courseClass } = req.body;
    const thumbnail = req.file ? req.file.filename : null;

    if (!subject) {
      return res.status(400).json({ message: "Subject is required" });
    }

    const course = await Course.create({
      name,
      slug,
      subject,
      class: courseClass,
      description,
      price,
      thumbnail,
      isPaid: price > 0
    });

    res.status(201).json(course);
  } catch (error){
    console.error("CREATE COURSE ERROR:", error)
    res.status(500).json({
      message:"Failed to create course",
      error: error.message
    });
  }
});

router.get("/courses/id/:id", requireAdmin, async (req, res) => {
  try {
    const course = await Course.findById(req.params.id);

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

    res.json(course);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

router.get("/courses", requireAdmin, async (req, res) => {
  try {
    const { class: courseClass } = req.query

    let filter = {
      $or: [
        {isArchived: false},
        { isArchived: {$exists: false}}
      ]
    }

    if (courseClass && courseClass !== "All") {
      filter.class = courseClass
    }

    const courses = await Course.find(filter).populate("subject", "name")
    res.json(courses)

    console.log("FILTER:", filter);
    console.log("COURSES FOUND:", courses.length);

  } catch (error) {
    res.status(500).json({ message: error.message })
  }
})

/* ================= PATCH ROUTES (ORDER MATTERS) ================= */

// 1️⃣ TOGGLE PAID
router.patch("/courses/:id/toggle-paid", requireAdmin, async (req, res) => {
  try {
    const course = await Course.findById(req.params.id)
    if (!course) {
      return res.status(404).json({ message: "Course not found" })
    }

    const updated = await Course.findByIdAndUpdate(
      req.params.id,
      {
        isPaid: !course.isPaid,
        price: course.isPaid ? 0 : course.price
      },
      { new: true }
    )

    res.json(updated)
  } catch (error) {
    res.status(500).json({ message: "Failed to toggle paid status" })
  }
})

// 2️⃣ TOGGLE ACTIVE
router.patch("/courses/:id/toggle-active", requireAdmin, async (req, res) => {
  try {
    const course = await Course.findById(req.params.id);

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

    course.isActive = !course.isActive;
    await course.save();

    res.json(course);
  } catch (error) {
    res.status(500).json({
      message: "Failed to toggle course status",
      error: error.message
    });
  }
});

// 3️⃣ TOGGLE FREEZE
router.patch("/courses/:id/toggle-freeze", requireAdmin, async (req, res) => {
  try {
    const course = await Course.findById(req.params.id)
    if (!course) {
      return res.status(404).json({ message: "Course not found" })
    }

    const updated = await Course.findByIdAndUpdate(
      req.params.id,
      { isFrozen: !course.isFrozen },
      { new: true }
    )

    res.json(updated)
  } catch (error) {
    console.error("TOGGLE FREEZE ERROR:", error)
    res.status(500).json({ message: "Failed to toggle freeze" })
  }
})

// 4️⃣ TOGGLE CONTENT LOCK
router.patch("/courses/:id/toggle-content-lock", requireAdmin, async (req, res) => {
  try {
    const course = await Course.findById(req.params.id)
    if (!course) {
      return res.status(404).json({ message: "Course not found" })
    }

    const updated = await Course.findByIdAndUpdate(
      req.params.id,
      { isContentLocked: !course.isContentLocked },
      { new: true }
    )

    res.json(updated)
  } catch (error) {
    console.error("TOGGLE CONTENT LOCK ERROR:", error)
    res.status(500).json({ message: "Failed to toggle content lock" })
  }
})

// TOGGLE COURSE ARCHIVE

router.patch("/courses/:id/archive", requireAdmin, async (req, res) => {
  try {
    const course = await Course.findById(req.params.id)

    if (!course) {
      return res.status(404).json({ message: "Course not found" })
    }

    const updated = await Course.findByIdAndUpdate(
      req.params.id,
      { isArchived: !course.isArchived },
      { new: true }
    )

    res.json(updated)
  } catch (error) {
    console.error("ARCHIVE ERROR:", error)
    res.status(500).json({ message: "Failed to archive course" })
  }
})

router.get("/courses/archived", requireAdmin, async (req, res) => {
  try {
    const courses = await Course.find({ isArchived: true })
      .populate("subject", "name")

    res.json(courses)
  } catch (error) {
    res.status(500).json({ message: error.message })
  }
})

// TOGGLE PERMANENTLY DELETE

router.delete("/courses/:id", requireAdmin, async (req, res) => {
  try {
    const deleted = await Course.findByIdAndDelete(req.params.id)

    if (!deleted) {
      return res.status(404).json({ message: "Course not found" })
    }

    res.json({ message: "Course permanently deleted" })
  } catch (error) {
    console.error("DELETE ERROR:", error)
    res.status(500).json({ message: "Failed to delete course" })
  }
})

// ================ //

router.patch(
  "/courses/:id",
  requireAdmin,
  upload.single("thumbnail"),
  async (req, res) => {
    try {
      const { name, description, isContentLocked, subject, class: className } = req.body

      const updateData = {
        ...(name !== undefined && { name }),
        ...(description !== undefined && { description }),
        ...(isContentLocked !== undefined && { isContentLocked }),
        ...(subject !== undefined && { subject }),
        ...(className !== undefined && { class: className })
      }

      // ✅ NEW: thumbnail update
      if (req.file) {
        updateData.thumbnail = req.file.filename
      }

      const updated = await Course.findByIdAndUpdate(
        req.params.id,
        updateData,
        { new: true }
      )

      if (!updated) {
        return res.status(404).json({ message: "Course not found" })
      }

      res.json(updated)

    } catch (error) {
      console.error("PATCH ERROR:", error)
      res.status(500).json({ message: "Failed to update course" })
    }
  }
)

module.exports = router;
