import { type Request, type Response } from "express";
import UserModel from '../models/userModel';

export default {

  create: async function (req: Request, res: Response) {
    const pass = req.body.pass;

    try {
      const userFound = await UserModel.findOne({ pass: pass });
      if (userFound) {
        return res.status(409).json({ message: 'User already exists' });
      }

      const user = new UserModel({
        pass,
        omdb_key: req.body.omdb_key,
        twitch_client_id: req.body.twitch_client_id,
        twitch_client_secret: req.body.twitch_client_secret,
        mac_address: req.body.mac_address,
      });

      await user.save();
      return res.redirect('/list');
    }
    catch (err) {
      return res.status(500).json({ message: 'Error when creating user', error: err });
    }
  },

  remove: async function (req: Request, res: Response) {
    try {
      await UserModel.deleteMany();
      return res.status(204).json({ message: 'User deleted' });
    } catch (err) {
      return res.status(500).json({ message: 'Error when deleting the user', error: err });
    }
  },

  get: async function (req: Request, res: Response) {
    try {
      const usersFound = await UserModel.find();

      return res.status(200).json(usersFound);
    } catch (err) {
      return res.status(500).json({ message: 'Error when getting the user', error: err });
    }
  },
};