import { EntityManager, Repository, getRepository } from 'typeorm'
import { Domain } from '@things-factory/shell'
import { User } from '@things-factory/auth-base'
import { ReleaseGood, DeliveryOrder, ORDER_INVENTORY_STATUS } from '@things-factory/sales-base'
import { Setting } from '@things-factory/setting-base'

const SETTINGS = {
  QC_SKU: 'qc-sku'
}

export const getDeliveryOrders = {
  async getDeliveryOrders(_: any, { releaseGoodNo }, context: any) {
    const { domain, tx }: { domain: Domain, tx: EntityManager } = context.state

    const releaseGood: ReleaseGood = await getRepository(ReleaseGood).findOne({
      where: { domain, name: releaseGoodNo },
      relations: ['orderInventories']
    })

    if (!releaseGood) {
      throw new Error(`ReleaseGood with name ${releaseGoodNo} not found`)
    }

    const complete_status = [ORDER_INVENTORY_STATUS.LOADED, ORDER_INVENTORY_STATUS.TERMINATED, ORDER_INVENTORY_STATUS.RETURNING, ORDER_INVENTORY_STATUS.MISSING]
    const completable = releaseGood.orderInventories?.every(oi => complete_status.includes(oi.status))
    
    const settingRepo: Repository<Setting> = tx?.getRepository(Setting) || getRepository(Setting)
    const qcSetting = await settingRepo.findOne({
      where: { domain, name: SETTINGS.QC_SKU }
    })

    const useQcSku =
      qcSetting?.value?.toString().toLowerCase().trim() === 'true'

    let deliveryOrders: DeliveryOrder[] = await getRepository(DeliveryOrder).find({
      where: { releaseGood },
      relations: ['orderInventories', 'orderInventories.inventory', 'orderInventories.product']
    })

    if (useQcSku) {
      deliveryOrders = deliveryOrders
      .map((do_) => {
        const liveOIs = do_.orderInventories.filter(
          (oi) => oi.status !== ORDER_INVENTORY_STATUS.TERMINATED
        )
        return { ...do_, orderInventories: liveOIs }
      }) 
      .filter((do_) => do_.orderInventories.length > 0)
    }

    return {
      completable: completable,
      deliveryOrders: deliveryOrders
    }
  }
}
