// Admin · Invites — create, list and revoke emailed account invites.
//
// Mounted at /api/v1/admin/invites by admin/index.js, which already applied
// `noindex, isLoggedIn, staffOnly`. Issuing an invite picks the new account's
// role, so it is admin-only — otherwise an editor could mint an admin.

const express = require('express')
const { body, param } = require('express-validator')

const invites = require('./invites.controller')
const { requireRole } = require('../../../utils/auth')
const validate = require('../../../middleware/validate')

const invitesRouter = express.Router()
const adminOnly = requireRole('admin')

invitesRouter.post(
  '/',
  // #swagger.tags = ['Admin · Invites']
  // #swagger.summary = 'Create and email an account invite at a chosen access level'
  // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
  /* #swagger.requestBody = { required: true, content: { "application/json": { schema: { type: "object", required: ["email","role"], properties: { email: { type: "string" }, role: { type: "string" } } } } } } */
  /* #swagger.responses[201] = { description: 'Invite created', content: { "application/json": { schema: { type: "object", additionalProperties: true } } } } */
  /* #swagger.responses[400] = { description: 'Validation error', content: { "application/json": { schema: { $ref: "#/components/schemas/ValidationError" } } } } */
  adminOnly,
  body('email').isEmail().isLength({ max: 255 }),
  body('role').isIn(['admin', 'editor', 'moderator', 'player']),
  validate,
  invites.create,
)
invitesRouter.get(
  '/',
  // #swagger.tags = ['Admin · Invites']
  // #swagger.summary = 'List recent invites (no tokens)'
  // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
  /* #swagger.responses[200] = { description: 'Invites, newest first', content: { "application/json": { schema: { type: "array", items: { type: "object", additionalProperties: true } } } } } */
  adminOnly,
  invites.list,
)
invitesRouter.delete(
  '/:id',
  // #swagger.tags = ['Admin · Invites']
  // #swagger.summary = 'Revoke a pending invite'
  // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
  // #swagger.parameters['id'] = { in: 'path', required: true, schema: { type: 'integer' }, description: 'Invite id.' }
  /* #swagger.responses[200] = { description: 'Revoked', content: { "application/json": { schema: { type: "object", additionalProperties: true } } } } */
  /* #swagger.responses[404] = { description: 'No pending invite to revoke', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
  adminOnly,
  param('id').isInt(),
  validate,
  invites.revoke,
)

module.exports = invitesRouter
