import { getRepository } from 'typeorm'

import { Sequence, SEQUENCE_TYPE } from '@things-factory/id-rule-base'
import { Domain, ListParam } from '@things-factory/shell'

export const productLabelReport = {
  async productLabelReport(_: any, params: ListParam, context: any) {
    try {
      const { domain }: { domain: Domain } = context.state
      // const { domain }: { domain: Domain } = context.state
      const bizplaceId = params.filters.find(data => data.name === 'bizplace').value
      const type = params.filters.find(data => data.name === 'type')?.value
      const fromDate = params.filters.find(data => data.name === 'fromDate').value
      const toDate = params.filters.find(data => data.name === 'toDate').value

      if (!bizplaceId || !fromDate || !toDate) throw new Error('Invalid input')

      const items = await getRepository(Sequence).query(`
        SELECT "date", "type", "count", "bizplace_id" FROM (
          SELECT
          "sq"."pattern"::JSONB ->> 'type' AS "type",
          "sq"."pattern"::JSONB ->> 'date' AS "date",
          "sq"."pattern"::JSONB ->> 'bizplaceId' AS "bizplace_id",
          "sq"."seq" AS "count"
          FROM "sequences" "sq" WHERE "sq"."type" = '${SEQUENCE_TYPE.PRODUCT_LABEL_COUNTER}'
          AND "sq"."domain_id" = '${domain.id}'
        ) AS foo
        WHERE "bizplace_id" = '${bizplaceId}'
        ${type ? `AND "type" ilike '%${type}%'` : ''}
        AND "date"::date BETWEEN '${fromDate}' AND '${toDate}'
        ORDER BY type ASC, date ASC
      `)

      // @farishelmi any usage for this function? If no please remove.
      /* 
      need to transform into queryBuilder form
      const qb: SelectQueryBuilder<Sequence> = tx
        .getRepository(Sequence)
        .createQueryBuilder('sq')
        .select(`"sq"."pattern"::JSONB ->> 'type'`, 'type')
        .addSelect(`"sq"."pattern"::JSONB ->> 'date'`, 'date')
        .addSelect(`"sq"."pattern"::JSONB ->> 'bizplaceId'`, 'bizplace_id')
        .addSelect(`"sq"."seq"`, 'count')
        .where('"sq"."type" = :sequenceType', { sequenceType: SEQUENCE_TYPE.PRODUCT_LABEL_COUNTER })
        .andWhere(`"sq"."pattern"::JSONB ->> 'bizplaceId' = :bizplaceId`, { bizplaceId })
        .andWhere(`"sq"."domain_id" = :domainId`, { domainId: domain.id }) 
      */

      return {
        items,
        total: 0
      }
    } catch (error) {
      throw error
    }
  }
}
