var { MovieModel, SeriesModel } = require('../models/mediaModel');

/**
 * mediaController.js
 *
 * @description :: Server-side logic for managing movies and series.
 */
module.exports = {

  /**
   * mediaController.list()
   */
  list: function (req, res) {
    const MediaModel = req.baseUrl.includes('movies') ? MovieModel : SeriesModel;

    MediaModel.find({}, { __v: 0 })
      .then(media => {
        return res.json(media);
      })
      .catch(err => {
        return res.status(500).json({
          message: 'Error when getting media.',
          error: err
        });
      });
  },

  /**
   * mediaController.create()
   */
  create: async function (req, res) {
    const mediaCode = req.body.code;
    const userFound = req.user;
    try {
      const MediaModel = req.baseUrl.includes('movies') ? MovieModel : SeriesModel;
      const mediaFound = await MediaModel.findOne({ code: mediaCode });
      if (mediaFound) {
        return res.status(409).json({ message: 'Media already exists' });
      }

      const uri = `http://www.omdbapi.com/?i=${mediaCode}&apikey=${userFound.omdb_key}`;
      const mJson = await fetch(uri);
      const mData = await mJson.json();

      if (mData.Response == 'False') {
        return res.status(404).json({ message: 'wrong code' });
      }

      const media = new MediaModel({
        code: mediaCode,
        title: mData.Title,
        released: mData.Released,
        webImg: mData.Poster,
      });

      const savedMedia = await media.save();
      return res.status(201).json(media);
    } catch (err) {
      return res.status(500).json({ message: 'Error when creating media' });
    }
  },

  /**
   * mediaController.delete()
   */
  remove: async function (req, res) {
    var id = req.body.code;

    try {

      const MediaModel = req.baseUrl.includes('movies') ? MovieModel : SeriesModel;
      const media = await MediaModel.findOneAndDelete({ code: id });
      if (!media) {
        return res.status(404).json({ message: 'No such media' });
      }

      return res.status(204).json();
    }
    catch (err) {
      return res.status(500).json({ message: 'Error when deleting the media.' });
    }
  },
};
