const _ = require('lodash');
const express = require('express');

module.exports = () => {
    var router = express.Router(); // eslint-disable-line

    const middleware = {
        organizations: require('../../../middlewares/organizations'),
        userData: require('../../../middlewares/userData'),
    };

    const profile = require('./profile');
    const owner = require('./owner');
    const dns = require('./dns');
    const customization = require('./customization');
    const restore = require('./restore');

    router.use(middleware.organizations);
    router.use(middleware.userData);

    router.use((req, res, next) => {
        // '/restore' - восстановление доступа к организации;
        // разрешено всем, поэтому пропускаем эту миддлвару
        if (/^\/restore($|\/)/.test(req.path)) {
            return next();
        }

        const organizations = _.get(req, 'context.organizations', []);

        const isAdmin = _.get(req, 'context.session.internal') ?
            _.get(req, 'context.currentUser.role') === 'admin' :
            Boolean(organizations.length);

        // если пользователь не админ, отдаем 403
        if (!isAdmin) {
            return res.sendStatus(403);
        }

        const orgId = _.get(req, 'context.state.organization');
        const currentOrganization = _.find(organizations, org => String(org.id) === orgId);

        req.admin_id = _.get(currentOrganization, 'admin_id');

        next();
    });

    router.route('/restore')
        .get(restore.getActiveChecks)
        .post(restore.start);

    router.route('/restore/ownership')
        .get(restore.getOwnershipStatus)
        .post(restore.checkOwnership);

    router.route('/restore/current-owner')
        .get(restore.getCurrentOwner);

    router.route('/profile')
        .get(profile.read)
        .put(profile.update)
        .patch(profile.update);

    router.route('/logo')
        .post(profile.setLogo)
        .delete(profile.removeLogo);

    router.route('/change-owner')
        .post(owner.change);

    router.route('/dns')
        .get(dns.getRecords)
        .post(dns.submitRecord)
        .delete(dns.removeRecord);

    router.route('/services')
        .post(customization.toggleService);

    return router;
};
