import { getRepository, SelectQueryBuilder } from 'typeorm'

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

export const collectionOrdersByStatusResolver = {
  async collectionOrdersByStatus(_: 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<CollectionOrder> = getRepository(CollectionOrder).createQueryBuilder('co')
    buildQuery(qb, params, context)
    return qb.select('co.status', 'status').addSelect('COUNT(*) AS count').groupBy('co.status').getRawMany()
  }
}
