const Video = require('../models/Video.js');
const Bhajan = require('../models/Bhajan.js');

const getVideos = async (req, res) => {
  try {
    const videos = await Video.getAll();
    res.json(videos);
  } catch (error) {
    console.error('Error fetching videos:', error);
    res.status(500).json({ message: 'Server error fetching videos.' });
  }
};

const getVideoById = async (req, res) => {
  try {
    const { id } = req.params;
    const video = await Video.getByIdOrVideoId(id);
    
    if (video) {
      res.json(video);
    } else {
      res.status(404).json({ message: 'Video not found.' });
    }
  } catch (error) {
    console.error('Error fetching video by ID:', error);
    res.status(500).json({ message: 'Server error fetching video.' });
  }
};

const createVideo = async (req, res) => {
  try {
    const { title, speaker, category, youtubeId, videoId, duration, description, isShort, thumbnail, publishDate, videoUrl } = req.body;

    const finalYoutubeId = youtubeId || videoId;
    if (!title || !finalYoutubeId) {
      return res.status(400).json({ message: 'Title and YouTube Video ID are required.' });
    }

    const newVideo = await Video.create({
      title,
      speaker,
      category,
      youtubeId: finalYoutubeId,
      videoId: videoId || youtubeId,
      duration,
      description,
      isShort,
      thumbnail,
      publishDate,
      videoUrl
    });

    res.status(201).json({
      message: 'Video added successfully.',
      video: newVideo
    });
  } catch (error) {
    console.error('Error creating video:', error);
    res.status(500).json({ message: 'Server error adding video.' });
  }
};

const deleteVideo = async (req, res) => {
  try {
    const { id } = req.params;
    const success = await Video.delete(id);

    if (success) {
      res.json({ message: 'Video deleted successfully.' });
    } else {
      res.status(404).json({ message: 'Video not found or already deleted.' });
    }
  } catch (error) {
    console.error('Error deleting video:', error);
    res.status(500).json({ message: 'Server error deleting video.' });
  }
};



const getLatest = async (req, res) => {
  try {
    const limit = req.query.limit || 5;
    const videos = await Video.getLatest(limit);
    res.json(videos);
  } catch (error) {
    console.error('Error fetching latest videos:', error);
    res.status(500).json({ message: 'Server error fetching latest videos.' });
  }
};



module.exports = {
  getVideos,
  getVideoById,
  createVideo,
  deleteVideo,
  getLatest
};
