import { EntityManager, Not, In } from 'typeorm'

import { User } from '@things-factory/auth-base'
import { Domain } from '@things-factory/shell'

import { ReleaseGood, ORDER_STATUS } from '@things-factory/sales-base'

export const assignSorter = {
  async assignSorter(
    _parentObj: void,
    { releaseGoodId, userId }: { releaseGoodId: [string]; userId: string },
    context: any
  ): Promise<void> {
    const { tx, domain }: { tx: EntityManager; domain: Domain } = context.state
    const sorter: User = await tx.getRepository(User).findOne(userId, { relations: ['domains'] })

    if ((sorter?.domains || []).every((userDomain: Domain) => userDomain.id !== domain.id)) {
      throw new Error('Target user does not belong to current domain')
    }
    if (!sorter) throw new Error('failed to find target user')

    await Promise.all(
      releaseGoodId.map(async releaseGoodId => {
        const releaseGood: ReleaseGood = await tx.getRepository(ReleaseGood).findOne(
          {
            id: releaseGoodId
          },
          {
            where: [
              {
                status: Not(In([ORDER_STATUS.PROCESSING, ORDER_STATUS.DONE]))
              }
            ]
          }
        )

        if (!releaseGood) throw new Error('failed to find target order')
        await tx.getRepository(ReleaseGood).update(
          {
            id: releaseGoodId
          },
          {
            sortedBy: sorter
          }
        )
      })
    )
  }
}
