import {expenseIdValidation, expenseValidation, groupMemberValidation, validate} from './validation.js';
import {Router} from 'express';
import {getCurrentUser} from './util.js';
import {ManageGroup} from '../core/manageGroup.js';

export function routes(db) {
  const router = Router();
  router.use(prepareGroupRequest);

  async function prepareGroupRequest(req, res, next) {
    const group = await db.getGroup(req.groupName);
    if (!group) return res.status(404).end();

    const manageGroup = new ManageGroup(group.name, db);
    await manageGroup.assertPermissionOf(req.jwtData.username);
    req.manageGroup = manageGroup;

    next();
  }

  router.get('/', async (req, res) => {
    res.json(await req.manageGroup.getGroup());
  });

  router.get('/members', async (req, res) => {
    res.json(await req.manageGroup.getUsersOfGroup());
  });

  router.get('/expenses', async (req, res) => {
    res.json(await req.manageGroup.getExpensesOfGroup());
  });

  router.post('/member', groupMemberValidation(), validate, async function (req, res) {
    await req.manageGroup.addUser(req.body.name);
    res.status(200).json({});
  });

  router.post('/expense', expenseValidation(), validate, async (req, res) => {
    await req.manageGroup.addExpense(
        await getCurrentUser(req, db),
        req.body.description,
        req.body.amount
    );

    res.status(200).json({});
  });

  router.delete('/expense/:id', expenseIdValidation(), validate, async (req, res) => {
    await req.manageGroup.deleteExpense(req.params.id);
    res.status(200).end();
  });

  router.post('/close', async (req, res) => {
    await req.manageGroup.closeGroup();
    res.status(200).end();
  });

  router.get('/settlements', async (req, res) => {
    res.json(await req.manageGroup.getSettlements());
  })

  return router;
}
