import RenewalSerializer from '@apps/subscriptions/serializers/renewal_serializer'
import Service from '@apps/subscriptions/models/service'
import Renewal from '@apps/subscriptions/models/renewal'

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

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

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

  const renewal = await Renewal.query(qb => {
    qb.innerJoin('subscriptions_subscriptions','subscriptions_subscriptions.id','subscriptions_renewals.subscription_id')
    qb.where('subscriptions_renewals.team_id', req.team.get('id'))
    qb.where('subscriptions_subscriptions.service_id', service.get('id'))
    qb.where('subscriptions_renewals.id', req.params.id)
  }).fetch({
    withRelated: ['invoice','plan','subscription','usages.resource'],
    transacting: req.trx
  })

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

  await res.status(200).respond(renewal, RenewalSerializer)

}

export default showRoute
