import { Args, Ctx, Query, Resolver } from 'type-graphql'

import { Process } from '../process/process'
import { config } from '@things-factory/env'
import { Favorite } from '@things-factory/fav-base'
import { buildQuery, getRepository, ListParam } from '@things-factory/shell'

import { ProcessFavorite, ProcessFavoriteList } from './process-favorite-type'

const ORMCONFIG = config.get('ormconfig', {})
const DATABASE_TYPE = ORMCONFIG.type

@Resolver(ProcessFavorite)
export class ProcessFavoriteQuery {
  @Query(returns => ProcessFavoriteList, { description: 'To fetch multiple ProcessFavorites' })
  async favoriteProcesses(@Args() params: ListParam, @Ctx() context: ResolverContext): Promise<ProcessFavoriteList> {
    const { user } = context.state

    const queryBuilder = getRepository(Process).createQueryBuilder()
    buildQuery(queryBuilder, params, context)

    var joinStatement = ''
    switch (DATABASE_TYPE) {
      case 'postgres':
        joinStatement = 'CAST(Process.id as VARCHAR) = Favorite.routing'
        break
      case 'sqlite':
      default:
        joinStatement = 'Process.id = Favorite.routing'
    }

    var qb = queryBuilder
      .innerJoin(Favorite, 'Favorite', joinStatement)
      .select([
        'Process.id as id',
        'Process.name as name',
        'Process.description as description',
        'Process.thumbnail as thumbnail',
        'Favorite.id as favoriteId'
      ])
      .andWhere('Favorite.user_id = :userId', {
        userId: user.id
      })

    const items = await qb.getRawMany()
    const total = await qb.getCount()

    return { items, total }
  }
}
