import { getRepository, SelectQueryBuilder } from 'typeorm'

import { User } from '@things-factory/auth-base'
import { getPermittedBizplaceIds } from '@things-factory/biz-base'
import { DeliveryOrder } from '@things-factory/sales-base'
import { buildQuery, Domain, ListParam } from '@things-factory/shell'

export const deliveryOrdersByStatusResolver = {
  async deliveryOrdersByStatus(_: any, params: ListParam, context: any) {
    const { domain, user }: { domain: Domain; user: User } = context.state

    if (!params.filters.find((filter: any) => filter.name === 'bizplace')) {
      params.filters.push({
        name: 'bizplaceId',
        operator: 'in',
        value: await getPermittedBizplaceIds(domain, user),
        relation: false
      })
    }

    const qb: SelectQueryBuilder<DeliveryOrder> = getRepository(DeliveryOrder).createQueryBuilder('do')
    buildQuery(qb, params, context)
    return qb.select('do.status', 'status').addSelect('COUNT(*) AS count').groupBy('do.status').getRawMany()
  }
}
