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

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

const createBhajan = async (req, res) => {
  try {
    const { title, singer, audio_url, category, duration, description, lyrics } = req.body;

    if (!title || !audio_url) {
      return res.status(400).json({ message: 'Title and Audio URL are required.' });
    }

    const newBhajan = await Bhajan.create({
      title,
      singer,
      audio_url,
      category,
      duration,
      description,
      lyrics
    });

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

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

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

const uploadAudio = async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({ message: 'No audio file uploaded.' });
    }
    
    const filePath = `/uploads/audio/${req.file.filename}`;
    
    res.json({
      message: 'Audio file uploaded successfully.',
      filePath
    });
  } catch (error) {
    console.error('Error uploading audio file:', error);
    res.status(500).json({ message: 'Server error uploading file.' });
  }
};

module.exports = {
  getBhajans,
  createBhajan,
  deleteBhajan,
  uploadAudio
};
