const db = require('../utils/db.js')

// import controller function.

const video = async(req, res, next)=>{
    const sql = `SELECT * FROM videos`;
    try {
        db.query(sql, (err,result)=>{
            if(err) return res.status(400).json({message:err})
            if(result.length==0) return res.status(400).json({message:'empty videos!'})
            res.status(200).json({message:'video found!', data:result})
        })
    } catch (error) {
        next(error)
    }
}

const create = async(req, res)=>{
    const sql = `INSERT INTO videos (title, url, type, status)
    VALUES(?,?,?,?) `;
    try {
          const {title, url, type, status} = req.body
            // prepare the data.
            db.query(sql, [title, url, type, status], (err,result)=>{
                if(err) return res.status(400).json({message:err})
                res.status(200).json({ message: "video is uploaded..", id:result.insertId});  
            })
    } catch (error) {
        console.error(error)
    }

}

const deleted = async(req, res, next)=>{
    const id = req.params.id;
    const sql = `DELETE FROM videos WHERE id = ?`;
    try {
        // all right deleted record.
        db.query(sql, [id], (error, result)=>{
        if(error) return res.status(400).json({message:error})
        res.status(203).json({message:'Video is deleted.'})
        })
    } catch (error) {
        next(error)
    }
}

module.exports = { video, create, deleted}