import Payment from "../models/payment.model.js"
import { verifyToken } from "../auth/auth.js"
import express from "express"
import mongoose from "mongoose"
import User from "../models/user.model.js"
import Student from "../models/student.model.js"

const paymentRouter = express.Router()

// add 

paymentRouter.post("/add", verifyToken, async(req, res) => {
    try {
        const { student, amount, date } = req.body
        if(!student || !amount || !date){
            return res.status(400).json({ message: "all fields are required"})
        }
        
        const isStudentTrue = await Student.findById(student)
        if(!isStudentTrue){
            return res.status(400).json({ message: "student doesn't exists"})
        }
        const payment = new Payment({ student, amount, date })
        await payment.save()
        return res.status(201).json({ message: "payment created successfully" })
    }catch(error){
        console.log(error)
        return res.status(500).json({ message: "server error"})
    }
})

// delete

paymentRouter.delete("/delete/:id", verifyToken, async(req, res) => {
    try {
        const { id } = req.params
        if(!mongoose.Types.ObjectId.isValid(id)) {
            return res.status(400).json({ message: "Invalid student ID" })
        }
        const deletedStudent = await Payment.findByIdAndDelete(id)
        if(!deletedStudent){
            return res.status(400).json({ message: "payment not found" })
        }
        return res.status(200).json({ message: "payment deleted successfully"})
    }catch(error){
        console.log(error)
        return res.status(500).json({ message: "server error"})
    }
})

// get all

paymentRouter.get("/all", verifyToken, async(req, res) => {
    try {
        const payments = await Payment.find().sort({ createdAt: -1 }).populate("student")
        return res.status(200).json({ payments })
    }catch(error){
        console.log(error)
        return res.status(500).json({ message: "server error"})
    }
})

// get by id

paymentRouter.get("/:id", verifyToken, async(req, res) => {
    try {
        const { id } = req.params
        if(!mongoose.Types.ObjectId.isValid(id)) {
            return res.status(400).json({ message: "Invalid student ID" })
        }
        const payment = await Payment.findById(id).populate("student")
        if(!payment){
            return res.status(404).json({ message: "payment not found" })
        }
        return res.status(200).json({ payment })
    }catch(error){
        console.log(error)
        return res.status(500).json({ message: "server error"})
    }
})
export default paymentRouter