// Admin · Email — outbound mail delivery via Gmail OAuth2.
//
// Mounted at /api/v1/admin/email by admin/index.js, which already applied
// `noindex, isLoggedIn, staffOnly`. The modern replacement for env SMTP: the
// refresh token is captured by the connect flow below and is write-only over
// this API (stored encrypted by utils/secretBox.js, never returned).
//
// Admin-only, and kept as a per-route gate rather than a router-level `use` so
// the middleware chain each route carries is unchanged by the move.

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

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

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

emailRouter.get(
  '/config',
  // #swagger.tags = ['Admin · Email']
  // #swagger.summary = 'Get email delivery config + status (admin only)'
  // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
  /* #swagger.responses[200] = { description: 'Config (refresh token stripped) + status', content: { "application/json": { schema: { type: "object", additionalProperties: true } } } } */
  /* #swagger.responses[401] = { description: 'Not authenticated', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
  /* #swagger.responses[403] = { description: 'Admin role required', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
  adminOnly,
  emailConfig.getConfig,
)
emailRouter.put(
  '/config',
  // #swagger.tags = ['Admin · Email']
  // #swagger.summary = 'Update email delivery config (admin only)'
  // #swagger.description = 'Set the From display name and enabled toggle. Enabling requires a connected Gmail account.'
  // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
  /* #swagger.requestBody = { content: { "application/json": { schema: { type: "object", properties: { senderName: { type: "string" }, enabled: { type: "boolean" } } } } } } */
  /* #swagger.responses[200] = { description: 'Updated config', content: { "application/json": { schema: { type: "object", additionalProperties: true } } } } */
  /* #swagger.responses[400] = { description: 'Cannot enable before connecting a mailbox', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
  /* #swagger.responses[401] = { description: 'Not authenticated', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
  /* #swagger.responses[403] = { description: 'Admin role required', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
  adminOnly,
  body('senderName').optional({ values: 'null' }).isString().trim().isLength({ max: 120 }),
  body('enabled').optional().isBoolean(),
  validate,
  emailConfig.saveConfig,
)
emailRouter.get(
  '/connect/start',
  // #swagger.tags = ['Admin · Email']
  // #swagger.summary = 'Begin the Gmail OAuth2 connect flow (admin only)'
  // #swagger.description = 'Returns { url } to redirect the browser to Google. Reuses the google SSO OAuth client.'
  // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
  /* #swagger.responses[200] = { description: 'Authorization URL', content: { "application/json": { schema: { type: "object", properties: { url: { type: "string" } } } } } } */
  /* #swagger.responses[400] = { description: 'Google OAuth client not configured', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
  /* #swagger.responses[401] = { description: 'Not authenticated', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
  /* #swagger.responses[403] = { description: 'Admin role required', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
  adminOnly,
  emailConfig.connectStart,
)
emailRouter.get(
  '/connect/callback',
  // #swagger.tags = ['Admin · Email']
  // #swagger.summary = 'OAuth2 callback — stores the refresh token, redirects to Settings'
  // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
  /* #swagger.responses[302] = { description: 'Redirect back to /admin/settings' } */
  adminOnly,
  emailConfig.connectCallback,
)
emailRouter.post(
  '/test',
  // #swagger.tags = ['Admin · Email']
  // #swagger.summary = 'Send a test email (admin only)'
  // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
  /* #swagger.requestBody = { content: { "application/json": { schema: { type: "object", properties: { to: { type: "string", format: "email" } } } } } } */
  /* #swagger.responses[200] = { description: 'Sent', content: { "application/json": { schema: { type: "object", properties: { sent: { type: "boolean" }, to: { type: "string" } } } } } } */
  /* #swagger.responses[502] = { description: 'Send failed / not configured', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
  adminOnly,
  body('to').optional({ values: 'falsy' }).isEmail().isLength({ max: 255 }),
  validate,
  emailConfig.testSend,
)
emailRouter.post(
  '/disconnect',
  // #swagger.tags = ['Admin · Email']
  // #swagger.summary = 'Disconnect Gmail and disable email (admin only)'
  // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
  /* #swagger.responses[200] = { description: 'Disconnected config', content: { "application/json": { schema: { type: "object", additionalProperties: true } } } } */
  /* #swagger.responses[401] = { description: 'Not authenticated', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
  /* #swagger.responses[403] = { description: 'Admin role required', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
  adminOnly,
  emailConfig.disconnect,
)

module.exports = emailRouter
