const fs = require('fs');
const path = require('path');
const router = require('express').Router();

module.exports = router;

const data = require('./units.json');
router.get('/', (req, res) => {
  // for every data set author from users and save it to authoredData variable
  const users = require('../users/users.json');
  const authoredData = data.map((unit) => {
    const user = users.find((user) => user.public_id == unit.author);
    let authoredUnit = undefined;
    if (user) {
      authoredUnit = { ...unit, author: user };
    }
    return authoredUnit;
  });

  res.send(authoredData);
});

router.post('/:id', (req, res) => {
  const id = parseInt(req.params.id);
  const updatedUnit = req.body;

  if (!updatedUnit) {
    return res.status(400).send('No unit to be added');
  }

  if (!data) {
    return res.status(500).send('No data to be updated');
  }

  const index = data.findIndex((unit) => unit.id === id);

  if (index < 0) {
    return res.status(404).send('Not found');
  }

  data.splice(index, 1);

  data.push({...updatedUnit, author: updatedUnit.author.public_id});

  res.status(200).send(data); 
});

router.put('/', (req, res) => {
  const newUnit = req.body;

  if (!newUnit) {
    return res.status(400).send('No new unit to be added');
  }

  if (!newUnit.author) {
    return res.status(400).send('User is not logged in!');
  }

  if (!data) {
    return res.status(500).send('No data to be updated');
  }

  const newId = data.length + 1;
  data.push({ ...newUnit, id: newId });

  res.status(200).send(data);
});

router.delete('/:id', (req, res) => {
  const id = parseInt(req.params.id);
  const index = data.findIndex((unit) => unit.id === id);

  if (index < 0) {
    return res.status(404).send('Not found');
  }

  data.splice(index, 1);
  res.send({ message: `Unit with ID ${id} deleted` });
});

router.get('/:id', (req, res) => {
  const users = require('../users/users.json');
  const id = parseInt(req.params.id);
  const unit = data.find((unit) => unit.id === id);

  if (!unit) {
    return res.status(404).send('Unit not found');
  }

  const user = users.find((user) => user.public_id == unit.author);

  res.send({...unit, author: user});
});
