"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = __importDefault(require("express"));
const express_async_handler_1 = __importDefault(require("express-async-handler"));
const sanitize_query_1 = __importDefault(require("../middleware/sanitize-query"));
const UsersService = __importStar(require("../services/users"));
const joi_1 = __importDefault(require("joi"));
const exceptions_1 = require("../exceptions");
const use_collection_1 = __importDefault(require("../middleware/use-collection"));
const router = express_1.default.Router();
router.use(use_collection_1.default('directus_users'));
router.post('/', sanitize_query_1.default, express_async_handler_1.default((req, res) => __awaiter(void 0, void 0, void 0, function* () {
    const primaryKey = yield UsersService.createUser(req.body, {
        role: req.role,
        admin: req.admin,
        ip: req.ip,
        userAgent: req.get('user-agent'),
        user: req.user,
    });
    const item = yield UsersService.readUser(primaryKey, req.sanitizedQuery, {
        role: req.role,
        admin: req.admin,
    });
    return res.json({ data: item || null });
})));
router.get('/', sanitize_query_1.default, express_async_handler_1.default((req, res) => __awaiter(void 0, void 0, void 0, function* () {
    const item = yield UsersService.readUsers(req.sanitizedQuery, {
        role: req.role,
        admin: req.admin,
    });
    return res.json({ data: item || null });
})));
router.get('/me', sanitize_query_1.default, express_async_handler_1.default((req, res) => __awaiter(void 0, void 0, void 0, function* () {
    if (!req.user) {
        throw new exceptions_1.InvalidCredentialsException();
    }
    const item = yield UsersService.readUser(req.user, req.sanitizedQuery, {
        role: req.role,
        admin: req.admin,
    });
    return res.json({ data: item || null });
})));
router.get('/:pk', sanitize_query_1.default, express_async_handler_1.default((req, res) => __awaiter(void 0, void 0, void 0, function* () {
    const items = yield UsersService.readUser(req.params.pk, req.sanitizedQuery, {
        role: req.role,
        admin: req.admin,
    });
    return res.json({ data: items || null });
})));
router.patch('/me', sanitize_query_1.default, express_async_handler_1.default((req, res) => __awaiter(void 0, void 0, void 0, function* () {
    if (!req.user) {
        throw new exceptions_1.InvalidCredentialsException();
    }
    const primaryKey = yield UsersService.updateUser(req.user, req.body, {
        role: req.role,
        admin: req.admin,
        ip: req.ip,
        userAgent: req.get('user-agent'),
        user: req.user,
    });
    const item = yield UsersService.readUser(primaryKey, req.sanitizedQuery, {
        role: req.role,
        admin: req.admin,
    });
    return res.json({ data: item || null });
})));
router.patch('/:pk', sanitize_query_1.default, express_async_handler_1.default((req, res) => __awaiter(void 0, void 0, void 0, function* () {
    const primaryKey = yield UsersService.updateUser(req.params.pk, req.body, {
        role: req.role,
        admin: req.admin,
        ip: req.ip,
        userAgent: req.get('user-agent'),
        user: req.user,
    });
    const item = yield UsersService.readUser(primaryKey, req.sanitizedQuery, {
        role: req.role,
        admin: req.admin,
    });
    return res.json({ data: item || null });
})));
router.delete('/:pk', express_async_handler_1.default((req, res) => __awaiter(void 0, void 0, void 0, function* () {
    yield UsersService.deleteUser(req.params.pk, {
        role: req.role,
        admin: req.admin,
        ip: req.ip,
        userAgent: req.get('user-agent'),
        user: req.user,
    });
    return res.status(200).end();
})));
const inviteSchema = joi_1.default.object({
    email: joi_1.default.string().email().required(),
    role: joi_1.default.string().uuid({ version: 'uuidv4' }).required(),
});
router.post('/invite', express_async_handler_1.default((req, res) => __awaiter(void 0, void 0, void 0, function* () {
    const { error } = inviteSchema.validate(req.body);
    if (error)
        throw new exceptions_1.InvalidPayloadException(error.message);
    yield UsersService.inviteUser(req.body.email, req.body.role, {
        role: req.role,
        admin: req.admin,
        ip: req.ip,
        userAgent: req.get('user-agent'),
        user: req.user,
    });
    res.end();
})));
const acceptInviteSchema = joi_1.default.object({
    token: joi_1.default.string().required(),
    password: joi_1.default.string().required(),
});
router.post('/invite/accept', express_async_handler_1.default((req, res) => __awaiter(void 0, void 0, void 0, function* () {
    const { error } = acceptInviteSchema.validate(req.body);
    if (error)
        throw new exceptions_1.InvalidPayloadException(error.message);
    yield UsersService.acceptInvite(req.body.token, req.body.password);
    res.end();
})));
exports.default = router;
