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

const ctrl = require('./public.controller')
const shard = require('./shard.controller')
const siteMode = require('../../../middleware/siteMode')
const validate = require('../../../middleware/validate')
const { contactLimiter } = require('../../../middleware/rateLimit')

const publicRouter = express.Router()

// Always available (so the client can render the maintenance page + contact).
publicRouter.get(
  '/settings',
  // #swagger.tags = ['Public']
  // #swagger.summary = 'Public site settings'
  // #swagger.description = 'Whitelisted, non-sensitive settings the client needs to render the site.'
  /* #swagger.responses[200] = { description: 'Key/value settings', content: { "application/json": { schema: { type: "object", additionalProperties: true } } } } */
  ctrl.getSettings,
)
publicRouter.get(
  '/status',
  // #swagger.tags = ['Public']
  // #swagger.summary = 'Site mode / status'
  // #swagger.description = 'Current site mode (live or maintenance) so the client can show the maintenance page.'
  /* #swagger.responses[200] = { description: 'Site status', content: { "application/json": { schema: { $ref: "#/components/schemas/PublicStatus" } } } } */
  ctrl.getStatus,
)
publicRouter.post(
  '/contact',
  // #swagger.tags = ['Public']
  // #swagger.summary = 'Send a contact message'
  // #swagger.description = 'Emails the site owner (or falls back to a mailto). Rate limited.'
  /* #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/ContactRequest" } } } } */
  /* #swagger.responses[200] = { description: 'Message sent', content: { "application/json": { schema: { $ref: "#/components/schemas/Message" } } } } */
  /* #swagger.responses[400] = { description: 'Validation error', content: { "application/json": { schema: { $ref: "#/components/schemas/ValidationError" } } } } */
  /* #swagger.responses[429] = { description: 'Too many messages (rate limited)', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
  /* #swagger.responses[502] = { description: 'Mail delivery failed', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
  contactLimiter,
  body('message').isString().trim().notEmpty().isLength({ max: 5000 }),
  body('email').optional({ values: 'falsy' }).isEmail(),
  body('name').optional({ values: 'falsy' }).isString().trim().isLength({ max: 100 }),
  validate,
  ctrl.contact,
)

// Content — gated by site mode (admins with a valid token bypass for preview).
publicRouter.get(
  '/posts/:category',
  // #swagger.tags = ['Public']
  // #swagger.summary = 'List published posts in a category'
  // #swagger.description = 'Gated by site mode: during maintenance only admins with a valid session see content.'
  // #swagger.parameters['category'] = { in: 'path', required: true, schema: { type: 'string' }, description: 'news | five-on-friday | newsletter | screenshots' }
  /* #swagger.responses[200] = { description: 'Published posts', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/Post" } } } } } */
  /* #swagger.responses[404] = { description: 'Unknown category', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
  siteMode,
  ctrl.getPosts,
)
publicRouter.get(
  '/posts/:category/:idOrSlug',
  // #swagger.tags = ['Public']
  // #swagger.summary = 'Get a single published post'
  // #swagger.parameters['category'] = { in: 'path', required: true, schema: { type: 'string' }, description: 'Post category.' }
  // #swagger.parameters['idOrSlug'] = { in: 'path', required: true, schema: { type: 'string' }, description: 'Numeric id or slug.' }
  /* #swagger.responses[200] = { description: 'The post', content: { "application/json": { schema: { $ref: "#/components/schemas/Post" } } } } */
  /* #swagger.responses[404] = { description: 'Unknown category or post not found', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
  siteMode,
  ctrl.getPost,
)
publicRouter.get(
  '/wiki',
  // #swagger.tags = ['Public']
  // #swagger.summary = 'List published wiki pages'
  /* #swagger.responses[200] = { description: 'Published wiki pages', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/WikiPage" } } } } } */
  siteMode,
  ctrl.getWikiList,
)
// Static paths must precede the :slug route so they aren't captured as a slug.
publicRouter.get(
  '/wiki/categories',
  // #swagger.tags = ['Public']
  // #swagger.summary = 'List wiki categories'
  /* #swagger.responses[200] = { description: 'Wiki categories', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/WikiCategory" } } } } } */
  siteMode,
  ctrl.getWikiCategories,
)
publicRouter.get(
  '/wiki/tags',
  // #swagger.tags = ['Public']
  // #swagger.summary = 'List wiki tags'
  /* #swagger.responses[200] = { description: 'Wiki tags', content: { "application/json": { schema: { type: "array", items: { type: "string" } } } } } */
  siteMode,
  ctrl.getWikiTags,
)
publicRouter.get(
  '/wiki/:slug',
  // #swagger.tags = ['Public']
  // #swagger.summary = 'Get a single published wiki page'
  // #swagger.parameters['slug'] = { in: 'path', required: true, schema: { type: 'string' }, description: 'Wiki page slug.' }
  /* #swagger.responses[200] = { description: 'The wiki page', content: { "application/json": { schema: { $ref: "#/components/schemas/WikiPage" } } } } */
  /* #swagger.responses[404] = { description: 'Not found', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
  siteMode,
  ctrl.getWikiPage,
)

// ── CMS pages (block-based) ────────────────────────────────────────────
// Preview is registered before /pages/:slug and is NOT site-mode gated, so a
// draft-preview link keeps working during maintenance. The token itself is the
// access control.
publicRouter.get(
  '/pages/:id/preview/:token',
  // #swagger.tags = ['Public']
  // #swagger.summary = 'Render a page from a draft-preview token'
  // #swagger.parameters['id'] = { in: 'path', required: true, schema: { type: 'integer' }, description: 'Page id.' }
  // #swagger.parameters['token'] = { in: 'path', required: true, schema: { type: 'string' }, description: 'Preview token from POST /admin/pages/:id/preview.' }
  /* #swagger.responses[200] = { description: 'The page (any status)', content: { "application/json": { schema: { type: "object", additionalProperties: true } } } } */
  /* #swagger.responses[404] = { description: 'Token invalid/expired or page missing', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
  ctrl.getPagePreview,
)
publicRouter.get(
  '/pages/:slug',
  // #swagger.tags = ['Public']
  // #swagger.summary = 'Get a published CMS page by slug'
  // #swagger.description = 'Drafts 404 for the public; staff sessions see drafts. Gated by site mode.'
  // #swagger.parameters['slug'] = { in: 'path', required: true, schema: { type: 'string' }, description: 'Page slug.' }
  /* #swagger.responses[200] = { description: 'The page', content: { "application/json": { schema: { type: "object", additionalProperties: true } } } } */
  /* #swagger.responses[404] = { description: 'Not found', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
  siteMode,
  ctrl.getPage,
)

// ── Shard live data (uo-link) ──────────────────────────────────────────────
// Token-free, same-origin reads. The status/feed/economy/idoc endpoints read
// the site's own ingested data; /char round-trips the live shard (cached). Not
// site-mode gated — shard status is useful even during site maintenance.
publicRouter.get(
  '/shard/status',
  // #swagger.tags = ['Public · Shard']
  // #swagger.summary = 'Shard connection state, online count and latest economy'
  /* #swagger.responses[200] = { description: 'Shard status', content: { "application/json": { schema: { $ref: "#/components/schemas/ShardStatus" } } } } */
  shard.getStatus,
)
publicRouter.get(
  '/shard/feed',
  // #swagger.tags = ['Public · Shard']
  // #swagger.summary = 'Recent notable shard events (from the ingested log)'
  // #swagger.parameters['kind'] = { in: 'query', required: false, schema: { type: 'string' }, description: 'Filter to a single event kind, e.g. vendor.sale.' }
  // #swagger.parameters['limit'] = { in: 'query', required: false, schema: { type: 'integer' }, description: 'Max rows (default 100, max 1000).' }
  /* #swagger.responses[200] = { description: 'Events, newest first', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/ShardEvent" } } } } } */
  query('kind').optional({ values: 'falsy' }).isString().isLength({ max: 48 }),
  query('limit').optional().isInt({ min: 1, max: 1000 }),
  validate,
  shard.getFeed,
)
publicRouter.get(
  '/shard/economy',
  // #swagger.tags = ['Public · Shard']
  // #swagger.summary = 'Gold-supply time series (oldest → newest)'
  // #swagger.parameters['limit'] = { in: 'query', required: false, schema: { type: 'integer' }, description: 'Max samples (default 100, max 1000).' }
  /* #swagger.responses[200] = { description: 'Economy samples', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/ShardEconomyPoint" } } } } } */
  query('limit').optional().isInt({ min: 1, max: 1000 }),
  validate,
  shard.getEconomy,
)
publicRouter.get(
  '/shard/online',
  // #swagger.tags = ['Public · Shard']
  // #swagger.summary = 'Staff online now (linked staff accounts; location is admin/moderator-only)'
  /* #swagger.responses[200] = { description: 'Online players', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/ShardOnlinePlayer" } } } } } */
  shard.getOnline,
)
publicRouter.get(
  '/shard/idoc',
  // #swagger.tags = ['Public · Shard']
  // #swagger.summary = 'Houses currently in danger (IDOC)'
  /* #swagger.responses[200] = { description: 'IDOC houses', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/ShardHouse" } } } } } */
  shard.getIdoc,
)
publicRouter.get(
  '/shard/champs',
  // #swagger.tags = ['Public · Shard']
  // #swagger.summary = 'Current champion-spawn board (all categories)'
  // #swagger.description = 'The live board of every champion / mini-champ / sea-boss spawn. Update in place via the champ.update / champ.remove frames on /shard/stream.'
  /* #swagger.responses[200] = { description: 'Champion spawns, ordered by name', content: { "application/json": { schema: { type: "array", items: { type: "object", additionalProperties: true } } } } } */
  shard.getChamps,
)
publicRouter.get(
  '/shard/guilds',
  // #swagger.tags = ['Public · Shard']
  // #swagger.summary = 'Current guild board (rosters, alliances, leaders)'
  // #swagger.description = 'The live board of every guild. Update in place via the guild.update / guild.remove / guild.join frames on /shard/stream.'
  /* #swagger.responses[200] = { description: 'Guilds, ordered by name', content: { "application/json": { schema: { type: "array", items: { type: "object", additionalProperties: true } } } } } */
  shard.getGuilds,
)
publicRouter.get(
  '/shard/governors',
  // #swagger.tags = ['Public · Shard']
  // #swagger.summary = 'Current town-governor board (City Loyalty)'
  // #swagger.description = 'One entry per city with its governor and election phase. Empty if the shard does not run the City Loyalty system. Live via city.update on /shard/stream.'
  /* #swagger.responses[200] = { description: 'Cities, ordered by name', content: { "application/json": { schema: { type: "array", items: { type: "object", additionalProperties: true } } } } } */
  shard.getGovernors,
)
publicRouter.get(
  '/shard/governors/:city/history',
  // #swagger.tags = ['Public · Shard']
  // #swagger.summary = 'Governor term history for a city'
  // #swagger.parameters['city'] = { in: 'path', required: true, schema: { type: 'string' }, description: 'City name, e.g. Britain.' }
  // #swagger.parameters['limit'] = { in: 'query', required: false, schema: { type: 'integer' }, description: 'Max terms (default 100, max 500).' }
  /* #swagger.responses[200] = { description: 'Terms, newest first', content: { "application/json": { schema: { type: "array", items: { type: "object", additionalProperties: true } } } } } */
  param('city').isString().isLength({ min: 1, max: 40 }),
  query('limit').optional().isInt({ min: 1, max: 500 }),
  validate,
  shard.getGovernorHistory,
)
publicRouter.get(
  '/shard/presence',
  // #swagger.tags = ['Public · Shard']
  // #swagger.summary = 'Online population aggregate (count + per-facet + per-region)'
  // #swagger.description = 'The latest presence.online snapshot powering the "Players Online" widget. Live via presence.online on /shard/stream.'
  /* #swagger.responses[200] = { description: 'Population snapshot', content: { "application/json": { schema: { type: "object", additionalProperties: true } } } } */
  shard.getPresence,
)
publicRouter.get(
  '/shard/houses',
  // #swagger.tags = ['Public · Shard']
  // #swagger.summary = 'House registry (owner, co-owners, price, decay)'
  // #swagger.description = 'Every house seen via the house.update registry feed. `price` is the placement value, not a for-sale flag. Live via house.update / house.remove on /shard/stream.'
  /* #swagger.responses[200] = { description: 'Houses, ordered by name', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/ShardHouse" } } } } } */
  shard.getHouses,
)
publicRouter.get(
  '/shard/stream',
  // #swagger.tags = ['Public · Shard']
  // #swagger.summary = 'Live shard event stream (Server-Sent Events, public/safe kinds)'
  // #swagger.description = 'text/event-stream of curated live events. Sensitive kinds (staff audit, cheat detection, login attempts, IPs) are NOT sent on this channel.'
  /* #swagger.responses[200] = { description: 'An SSE stream (Content-Type: text/event-stream).' } */
  shard.stream,
)

module.exports = publicRouter
