const cds = require('../../../cds')
const { toODataResult } = require('../utils/event')

/**
 * Provide localized metadata handler.
 *
 * @param {Object} service
 * @param {Object} options
 * @return {Function}
 */
const metadata = (service, options) => {
  return async (req, res, next) => {
    const locale = res.getContract().getLocale()

    const tenantId = req._inRequest.authInfo ? req._inRequest.authInfo.identityZone : undefined

    if (tenantId && cds.mtx && service._isExtended) {
      try {
        const edmx = await cds.mtx.getEdmx(tenantId, service.name, locale)
        return next(null, toODataResult(edmx))
      } catch (err) {
        return next(err)
      }
    }

    let localized
    if (cds.env.features && cds.env.features.snapi) {
      const compileOpts = Object.assign({ service: options.service }, service.model.meta.options)
      compileOpts.version = compileOpts.odataVersion
      localized = cds.localize(service.model, locale, cds.compile.to.edmx(service.model, compileOpts))
    } else {
      localized = cds.localize(
        service._csn,
        locale,
        cds.compile.to.edmx(service._csn, { version: options.version || 'v4', service: options.service })
      )
    }

    return next(null, toODataResult(localized))
  }
}

module.exports = metadata
