import 'dotenv/config'
import Fastify from 'fastify'
import cors from '@fastify/cors'
import jwt from '@fastify/jwt'
import multipart from '@fastify/multipart'
import fastifyStatic from '@fastify/static'
import path from 'node:path'
import { ensureAdminUser } from './lib/bootstrap-admin.js'
import { getOrCreateUnspecifiedCategory } from './lib/default-category.js'
import { getMaxUploadBodyBytes, getProductImageMaxFileBytes } from './lib/upload-limits.js'
import { registerAuth } from './plugins/auth.js'
import { registerApiRoutes } from './routes/api.js'
import { registerAuthRoutes } from './routes/auth.js'
import { registerUserAddressRoutes } from './routes/user-addresses.js'
import { registerUserCartRoutes } from './routes/user-cart.js'
import { registerUserMessageRoutes } from './routes/user-messages.js'
import { registerUserOrderRoutes } from './routes/user-orders.js'
import { registerUserPaymentRoutes } from './routes/user-payments.js'
import { registerOAuthSocialRoutes } from './routes/oauth-social.js'
import { registerUploadsResized } from './routes/uploads-resized.js'

const port = Number(process.env.PORT) || 3333
const origin = (process.env.CORS_ORIGIN ?? '')
  .split(',')
  .map((s) => s.trim())
  .filter(Boolean)

const fastify = Fastify({
  logger: true,
  bodyLimit: getMaxUploadBodyBytes(),
})

await fastify.register(cors, {
  origin: origin.length ? origin : true,
  credentials: true,
})

await fastify.register(jwt, {
  secret: process.env.JWT_SECRET || 'dev-jwt-secret-change-me',
})

await fastify.register(multipart, {
  limits: {
    files: 10,
    /** Совпадает с лимитом одного файла для `POST /api/admin/uploads` (товары, галерея). */
    fileSize: getProductImageMaxFileBytes(),
  },
})

registerUploadsResized(fastify)

const uploadsDir = path.join(process.cwd(), 'uploads')
await fastify.register(fastifyStatic, {
  root: uploadsDir,
  prefix: '/uploads/',
  setHeaders(res, filePath) {
    if (filePath.includes('/.cache/')) {
      res.setHeader('Cache-Control', 'public, max-age=31536000, immutable')
    } else {
      res.setHeader('Cache-Control', 'public, max-age=86400')
    }
  },
})

fastify.decorate('authenticate', async function authenticate(request, reply) {
  try {
    await request.jwtVerify()
  } catch {
    return reply.code(401).send({ error: 'Не авторизован' })
  }
})

registerAuth(fastify)
await registerAuthRoutes(fastify)
await registerUserAddressRoutes(fastify)
await registerUserCartRoutes(fastify)
await registerUserMessageRoutes(fastify)
await registerUserOrderRoutes(fastify)
await registerUserPaymentRoutes(fastify)
await registerOAuthSocialRoutes(fastify)
await registerApiRoutes(fastify)
await ensureAdminUser()
await getOrCreateUnspecifiedCategory()

fastify.get('/health', async () => ({ ok: true }))

try {
  await fastify.listen({ port, host: '0.0.0.0' })
} catch (err) {
  fastify.log.error(err)
  process.exit(1)
}
