import {
  Args,
  Mutation,
  Parent,
  Query,
  ResolveField,
  Resolver,
  Subscription,
} from '@nestjs/graphql';
import { TicketValidationState } from '@prisma/client';
import { TourObjectType } from '../app-accounting/tour.object-type';
import { DocumentInfoArgs, TicketsArgs } from './ticket-arg.types';
import { TicketSystemService } from './ticket-system.service';
import {
  PaginatedTicketObjectType,
  TicketObjectType,
  TicketStateKeyFiguresObjectType,
  TicketStateMetaObjectType,
  TicketsUpdatedObjectType,
} from './ticket.object-type';

@Resolver(() => TicketObjectType)
export class TicketsResolver {
  constructor(private readonly ticketsService: TicketSystemService) {}

  @Query(() => TicketObjectType)
  ticket(@Args('id') id: string) {
    return this.ticketsService.findById(id);
  }

  @Query(() => PaginatedTicketObjectType)
  tickets(@Args() { state, filters, cursor, take }: TicketsArgs) {
    return this.ticketsService.paginateTicketsByState(
      state,
      filters,
      take,
      cursor,
    );
  }

  @Query(() => [TicketObjectType])
  searchTickets(@Args('query') query: string) {
    return this.ticketsService.searchTickets(query);
  }

  // TODO: obsolete
  @Query(() => TicketStateMetaObjectType)
  ticketStateMeta(
    @Args('state', { type: () => TicketValidationState })
    ticketState: TicketValidationState,
  ) {
    return this.ticketsService.getTicketStateMeta(ticketState);
  }

  // TODO: obsolete
  @Query(() => TicketStateKeyFiguresObjectType)
  ticketStateKeyFigures(
    @Args('state', { type: () => TicketValidationState })
    ticketState: TicketValidationState,
  ) {
    return this.ticketsService.getTicketStateKeyFigures(ticketState);
  }

  @Mutation(() => TicketObjectType)
  setDocumentInfo(
    @Args('ticketId', { type: () => String }) ticketId: string,
    @Args() { approval, tdLocation }: DocumentInfoArgs,
  ) {
    return this.ticketsService.updateDocumentInfo(ticketId, {
      approval,
      tdLocation,
    });
  }

  @ResolveField(() => [TourObjectType])
  tours(@Parent() ticket: TicketObjectType) {
    return this.ticketsService.findToursByTicketId(ticket.id);
  }

  @Subscription(() => TicketsUpdatedObjectType)
  ticketsUpdated() {
    return this.ticketsService.pubSub.asyncIterableIterator('ticketsUpdated');
  }
}
