import VersionSerializer from '@apps/maha/serializers/version_serializer'
import Template from '@apps/websites/models/template'
import Website from '@apps/websites/models/website'
import Version from '@apps/maha/models/version'

const listRoute = async (req, res) => {

  const website = await Website.query(qb => {
    qb.where('team_id', req.team.get('id'))
    qb.where('id', req.params.website_id)
  }).fetch({
    transacting: req.trx
  })

  if(!website) return res.status(404).respond({
    code: 404,
    message: 'Unable to load website'
  })

  const template = await Template.query(qb => {
    qb.where('website_id', website.get('id'))
    qb.where('id', req.params.template_id)
    qb.whereNull('websites_templates.deleted_at')
  }).fetch({
    transacting: req.trx
  })

  if(!template) return res.status(404).respond({
    code: 404,
    message: 'Unable to load template'
  })

  const versions = await Version.query(qb => {
    qb.where('versionable_type', 'websites_templates')
    qb.where('versionable_id', template.get('id'))
    qb.where('key', 'config')
    qb.where('team_id', req.team.get('id'))
    qb.orderBy('created_at', 'desc')
  }).fetchAll({
    withRelated: ['user'],
    transacting: req.trx
  })

  await res.status(200).respond(versions, VersionSerializer)

}

export default listRoute
