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

module.exports = router;

let data = require('./users.json');
const path = require('path');
router.get('/', (req, res) => {
  res.send(data);
});

router.post('/', (req, res) => {
  const newUser = req.body;
  
  data.push(newUser);
  fs.writeFileSync(path.join(__dirname, 'users.json'), JSON.stringify(data));
  res.send(data);
});

router.post('/login', (req, res) => {
  const { email, password } = req.body;
  const user = data.find((user) => user.email === email && user.password === password);

  if (!user) {
    res.status(404).send('Пользователь не найден');
  }
  res.json({ public_id: user.public_id });
});

router.get('/account', (req, res) => {
  const { public_id } = req.query;
  const user = data.find((user) => user.public_id == public_id);

  if (!user) {
    res.status(404).send('Пользователь не найден');
  }
  res.send({ ...user, id: -1 });
});

router.post('/account/save', (req, res) => {
  const updatedUser = req.body;
  const { public_id } = updatedUser;
  const index = data.findIndex((user) => user.public_id == public_id);

  if (!index || index === -1) {
    res.status(404).send('Пользователь не найден');
  }

  data[index] = { ...data[index], ...updatedUser, id: data[index].id, password: data[index].password };
  fs.writeFileSync(path.join(__dirname, 'users.json'), JSON.stringify(data));

  res.status(200);
});
