import '@things-factory/auth-base' /* for Resolver Context */

import { Resolver, Query, FieldResolver, Root, Args, Arg, Ctx, Directive } from 'type-graphql'
import { getRepository } from '@things-factory/shell'
import { Analysis } from './analysis'
import { Process } from '../process/process'
import { AnalysisAvailability } from './analysis-type'

@Resolver(Process)
export class ProcessQuery {
  @FieldResolver(type => Analysis)
  async analysis(@Root() process: Process): Promise<Analysis> {
    return await getRepository(Analysis).findOneBy({ process: { id: process.id } })
  }
}

@Resolver(Analysis)
export class AnalysisQuery {
  @Query(returns => Analysis!, { nullable: true, description: 'To fetch a Analysis' })
  async analysis(@Arg('id') id: string, @Ctx() context: ResolverContext): Promise<Analysis> {
    return await getRepository(Analysis).findOne({
      where: { id }
    })
  }

  @Query(returns => AnalysisAvailability, { description: 'To check the availability of a Analysis dag' })
  async checkAnalysisAvailability(
    @Arg('id') id: string,
    @Ctx() context: ResolverContext
  ): Promise<AnalysisAvailability> {
    var analysis = {
      process: { id: id }
    } as Analysis

    const repository = getRepository(Analysis)
    analysis = (await repository.findOneBy(analysis as any)) || analysis

    return {
      result: analysis?.availiability || false,
      detail: analysis?.availDetail || ''
    }
  }
}
