import { authenticate } from '../../plugins/auth.js'
import {
  signInAnonymous,
  refreshTokens,
  logout,
} from '../../services/auth.service.js'

const extractDeviceInfo = (request) => ({
  user_agent: request.headers['user-agent'] || null,
  ip: request.ip || null,
})

const sendAuthError = (reply, err) => {
  if (!err.statusCode) reply.request.log.error({ err }, 'Unhandled auth error')
  return reply.code(err.statusCode || 500).send({
    success: false,
    error: {
      code: err.code || 'INTERNAL',
      message: err.message,
      ...(err.details && { details: err.details }),
    },
  })
}

export const sharedAuthRoutes = async (app) => {
  // Issue an anonymous customer session
  app.post('/anonymous', async (request, reply) => {
    try {
      const { tokens, profile } = await signInAnonymous({ deviceInfo: extractDeviceInfo(request) })
      return reply.code(201).send({ success: true, data: { ...tokens, profile } })
    } catch (err) {
      return sendAuthError(reply, err)
    }
  })

  // Rotate refresh token
  app.post('/refresh', async (request, reply) => {
    const { refresh_token } = request.body || {}
    if (!refresh_token) {
      return reply.code(422).send({
        success: false,
        error: { code: 'VALIDATION_ERROR', message: 'refresh_token is required' },
      })
    }
    try {
      const { tokens, profile } = await refreshTokens({
        refreshToken: refresh_token,
        deviceInfo: extractDeviceInfo(request),
      })
      return reply.send({ success: true, data: { ...tokens, profile } })
    } catch (err) {
      return sendAuthError(reply, err)
    }
  })

  // Logout — revoke current session
  app.post('/logout', { preHandler: authenticate }, async (request, reply) => {
    await logout({ sessionId: request.auth.sessionId })
    return reply.send({ success: true })
  })
}
