const express = require("express")
const User = require("../../models/User")

const router = express.Router()

router.get("/pending", async (req, res) => {
  try {
    const users = await User.find({
      role: "student",
      status: "pending"
    }).select("-password")

    res.json(users)
  } catch (error) {
    console.error("PENDING USERS ERROR ->", error)
    res.status(500).json({ message: "Failed to fetch pending users" })
  }
})


router.get("/all", async (req, res) => {
  try {
    const users = await User.find({ role: "student" }).select("-password")
    res.json(users)
  } catch (error) {
    res.status(500).json({ message: "Failed to fetch users" })
  }
})

router.patch("/:id/approve", async (req, res) => {
  try {
    const user = await User.findByIdAndUpdate(
      req.params.id,
      { status: "active" },
      { new: true }
    ).select("-password")

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

    res.json({
      message: "Student approved",
      user
    })
  } catch (error) {
    console.error("APPROVE ERROR ->", error)
    res.status(500).json({ message: "Approval failed" })
  }
})


router.patch("/:id/freeze", async (req, res) => {
  try {
    const user = await User.findByIdAndUpdate(
      req.params.id,
      { status: "frozen" },
      { new: true }
    ).select("-password")

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

    res.json({
      message: "Student frozen",
      user
    })
  } catch (error) {
    console.error("FREEZE ERROR ->", error)
    res.status(500).json({ message: "Freeze failed" })
  }
})


router.patch("/:id/reset-password", async (req, res) => {
  try {
    const { newPassword } = req.body

    if (!newPassword) {
      return res.status(400).json({ message: "New password required" })
    }

    const user = await User.findById(req.params.id)
    if (!user) {
      return res.status(404).json({ message: "User not found" })
    }

    user.password = newPassword
    await user.save()

    res.json({ message: "Password reset successful" })
  } catch (error) {
    console.error("RESET PASSWORD ERROR ->", error)
    res.status(500).json({ message: "Reset failed" })
  }
})


router.delete("/:id", async (req, res) => {
  try {
    const user = await User.findByIdAndDelete(req.params.id)

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

    res.json({ message: "Student deleted" })
  } catch (error) {
    console.error("DELETE USER ERROR ->", error)
    res.status(500).json({ message: "Delete failed" })
  }
})

router.patch("/:id/assign/:courseId", async (req, res) => {
  try {
    const { id, courseId } = req.params

    const user = await User.findById(id)

    const exists = user.purchasedCourses.includes(courseId)

    if (exists) {
      user.purchasedCourses.pull(courseId)
    } else {
      user.purchasedCourses.push(courseId)
    }

    await user.save()

    res.json({
      message: exists ? "Course unassigned" : "Course assigned"
    })
  } catch (err) {
    res.status(500).json({ message: "Assign toggle failed" })
  }
})

router.put("/assign-batch", async (req, res) => {
  try{
    const { userId, batchId } = req.body

    const user = await User.findById(userId)

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

    user.batch = batchId
    await user.save()

    res.json({ message: "Student assigned to batch "})

  } catch (error) {
    res.status(500).json({
      message: "Failed to assign batch",
      error: error.message
    })
  }
})

router.patch("/:id/lock/:courseId", async (req, res) => {
  try {
    const { id, courseId } = req.params

    const user = await User.findById(id)

    const exists = user.lockedCourses.includes(courseId)

    if (exists) {
      user.lockedCourses.pull(courseId)
    } else {
      user.lockedCourses.push(courseId)
    }

    await user.save()

    res.json({
      message: exists ? "Course unlocked" : "Course locked"
    })
  } catch (err) {
    res.status(500).json({ message: "Lock toggle failed" })
  }
})

router.patch("/:id/update", async (req, res) => {
  try {
    const { name, email, mobile } = req.body

    const user = await User.findByIdAndUpdate(
      req.params.id,
      { name, email, mobile },
      { new: true }
    )

    res.json(user)
  } catch (err) {
    res.status(500).json({ message: "Update failed" })
  }
})

router.post("/create", async (req, res) => {
  try {
    const { name, email, password, mobile } = req.body

    const exists = await User.findOne({ email })
    if (exists) {
      return res.status(400).json({ message: "User already exists" })
    }

    const bcrypt = require("bcrypt")
    const hashed = await bcrypt.hash(password, 10)

    const user = await User.create({
      name,
      email,
      password: password,
      mobile,
      role: "student",
      status: "active",
      registrationType: "admin"
    })

    res.status(201).json(user)
  } catch (err) {
    console.error("ADMIN CREATE USER ERROR:", err)
    res.status(500).json({ message: "Create failed" })
  }
})

router.get("/users", async (req, res) => {
  try{
    const users = await User.find({ role: "student" })
      .select("name class")

    res.json(users)

  } catch (error) {
    res.status(500).json({
      message: "Failed to fetch users",
      error: error.message
    })
  }
})

module.exports = router
