import DealSerializer from '@apps/sales/serializers/deal_serializer'
import Transition from '@apps/sales/models/transition'
import { audit } from '@core/services/routes/audit'
import socket from '@core/services/routes/emitter'
import Stage from '@apps/sales/models/stage'
import Deal from '@apps/sales/models/deal'
import moment from 'moment'

const getStory = (probability) => {
  if(probability === 100) return 'marked won'
  if(probability === 0) return 'marked lost'
  return 'stage changed'
}

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

  const deal = await Deal.query(qb => {
    qb.innerJoin('sales_pipelines','sales_pipelines.id','sales_deals.pipeline_id')
    qb.joinRaw('inner join crm_program_user_access on crm_program_user_access.program_id=sales_pipelines.program_id and crm_program_user_access.user_id=?', req.user.get('id'))
    qb.where('sales_deals.team_id', req.team.get('id'))
    qb.where('sales_deals.id', req.params.id)
  }).fetch({
    withRelated: ['contact.photo','owner.photo','pipeline','stage','last_transition'],
    transacting: req.trx
  })

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

  const stage = await Stage.query(qb => {
    qb.where('id', req.body.stage_id)
  }).fetch({
    transacting: req.trx
  })

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

  await deal.related('last_transition').save({
    completed_at: moment()
  }, {
    transacting: req.trx,
    patch: true
  })

  await Transition.forge({
    team_id: req.team.get('id'),
    deal_id: deal.get('id'),
    stage_id: stage.get('id'),
    description: req.body.description,
    probability: stage.get('probability')
  }).save(null, {
    transacting: req.trx
  })

  await deal.save({
    closed_at: stage.get('probability') % 100 === 0 ? moment() : null
  }, {
    transacting: req.trx,
    patch: true
  })

  await audit(req, {
    story: getStory(stage.get('probability')),
    auditable: deal
  })

  await socket.refresh(req, [
    `/admin/sales/pipelines/${deal.get('pipeline_id')}/deals`,
    `/admin/crm/contacts/${deal.get('contact_id')}/deals`,
    `/admin/sales/deals/${deal.get('id')}`,
    '/admin/sales/deals'
  ])

  await res.status(200).respond(deal, DealSerializer)

}

export default stageRoute
