import { getRepository, SelectQueryBuilder } from 'typeorm'

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

export const releaseGoodsByStatusResolver = {
  async releaseGoodsByStatus(_: any, params: ListParam, context: any) {
    const { domain, user }: { domain: Domain; user: User } = context.state
    const bizplaceId: string = params.filters.find((filter: any) => filter.name === 'bizplace')?.value || 'ALL'
    params.filters = params.filters.filter(filter => filter.name !== 'bizplace')
    const v4 = new RegExp(/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i)
    let bizplaceIds: string

    if (bizplaceId && (bizplaceId == 'ALL' || bizplaceId.match(v4))) {
      let bizplaces: string[] =
        bizplaceId && bizplaceId != 'ALL' ? [bizplaceId] : await getPermittedBizplaceIds(domain, user)
      bizplaceIds = bizplaces
        .map(bizplace => {
          return "'" + bizplace?.trim() + "'"
        })
        .join(',')
    } else throw new Error('invalid bizplaceId')

    const qb: SelectQueryBuilder<ReleaseGood> = getRepository(ReleaseGood).createQueryBuilder('rg')
    buildQuery(qb, params, context)
    return qb
      .select('rg.status', 'status')
      .addSelect('COUNT(*) AS count')
      .andWhere(`rg.bizplace_id IN (${bizplaceIds})`)
      .groupBy('rg.status')
      .getRawMany()
  }
}
