import { getRepository, In } from 'typeorm'
import { User } from '@things-factory/auth-base'
import { Domain } from '@things-factory/shell'
import { Worksheet, WORKSHEET_STATUS, WORKSHEET_TYPE } from '@things-factory/worksheet-base'
import { ReleaseGood } from '@things-factory/sales-base'

export const myLoadingAssignmentStatus = {
  async myLoadingAssignmentStatus(_parentObj: void, _params: void, context: any) {
    const { domain, user }: { domain: Domain; user: User } = context.state

    // Fetch Release Orders where sorter id = user id
    const releaseOrders: ReleaseGood[] = await getRepository(ReleaseGood).find({
      where: { domain, sortedBy: user }
    })

    // Fetch Worksheets where type = loading and release good id is in the fetched release orders
    const loadingWorksheets: Worksheet[] = await getRepository(Worksheet).find({
      where: {
        domain,
        type: WORKSHEET_TYPE.LOADING,
        releaseGood: In(releaseOrders.map(ro => ro.id)),
        status: In([WORKSHEET_STATUS.DEACTIVATED, WORKSHEET_STATUS.EXECUTING])
      }
    })

    return (loadingWorksheets || []).reduce(
      (assignmentStatus, worksheet: Worksheet) => {
        if (worksheet.status === WORKSHEET_STATUS.DEACTIVATED) assignmentStatus.pending.push(worksheet)
        if (worksheet.status === WORKSHEET_STATUS.EXECUTING) assignmentStatus.loading.push(worksheet)
        return assignmentStatus
      },
      { userId: user.id, pending: [], loading: [] }
    )
  }
}
