const express = require('express');

const BuyerPortalService = require('../services/buyer_portal');
const wrapAsync = require('../helpers').wrapAsync;
const { checkPermissions } = require('../middlewares/check-permissions');

const router = express.Router();

const workspacePermissions = ['READ_BUYER_PORTAL'];

const createSavedListPermissions = [
  'READ_BUYER_PORTAL',
  'CREATE_SAVED_LISTS',
  'CREATE_SAVED_LIST_ITEMS',
];

const createOrderPermissions = [
  'READ_BUYER_PORTAL',
  'CREATE_ORDERS',
  'CREATE_ORDER_ITEMS',
];

const createSampleRequestPermissions = [
  'READ_BUYER_PORTAL',
  'CREATE_SAMPLE_REQUESTS',
];

router.get(
  '/workspace',
  ...workspacePermissions.map((permission) => checkPermissions(permission)),
  wrapAsync(async (req, res) => {
    const workspace = await BuyerPortalService.workspace(
      {
        accountId: req.query.accountId,
        locationId: req.query.locationId,
      },
      req.currentUser,
    );

    res.status(200).send(workspace);
  }),
);

router.post(
  '/saved-lists',
  ...createSavedListPermissions.map((permission) =>
    checkPermissions(permission),
  ),
  wrapAsync(async (req, res) => {
    const savedList = await BuyerPortalService.createSavedList(
      req.body,
      req.currentUser,
    );

    res.status(200).send({ savedList });
  }),
);

router.post(
  '/orders',
  ...createOrderPermissions.map((permission) => checkPermissions(permission)),
  wrapAsync(async (req, res) => {
    const order = await BuyerPortalService.createOrder(
      req.body,
      req.currentUser,
    );

    res.status(200).send({ order });
  }),
);

router.post(
  '/sample-requests',
  ...createSampleRequestPermissions.map((permission) =>
    checkPermissions(permission),
  ),
  wrapAsync(async (req, res) => {
    const sampleRequest = await BuyerPortalService.createSampleRequest(
      req.body,
      req.currentUser,
    );

    res.status(200).send({ sampleRequest });
  }),
);

module.exports = router;
