import { Args, Context, Mutation, Resolver } from '@nestjs/graphql';
import { Apparatus } from '../models/Apparatus';
import { Client } from '../../client';
import { ApparatusService } from '../apparatus.service';
import { HttpException } from '@nestjs/common';
import {UUID} from '../../global/scalars/UUID'
import {pubsub} from '../../main'

@Resolver(() => Apparatus)
export class ApparatusResolverM {
  constructor(
    private readonly service: ApparatusService,
  ) {}

  @Mutation(() => Apparatus, { nullable: false })
  async ApparatusUpdate(
    @Context('client') client: Client,
    @Args('id', { type: () => UUID, nullable: false }) id: UUID,
    @Args('name', { nullable: true }) name?: string,
    @Args('logo', { nullable: true }) logo?: string,
  ): Promise<Apparatus> {
    if (!client.isMaster()) throw new HttpException('Access denied', 403);

    const tmp = await this.service.findOneById(id);

    const set: {
      name?: string
      logo?: string
    } = {};

    if (name !== undefined && name !== tmp.name) set.name = name
    if (logo !== undefined && logo !== tmp.logo) set.logo = logo

    if (Object.values(set).length === 0) return tmp;

    const neu = await this.service.update(client, tmp._id, {$set: set});
    pubsub.publish('ApparatusUpdated', { ApparatusUpdated: neu });
    return neu;
  }

  @Mutation(() => Apparatus, { nullable: false })
  async ApparatusCreate(
    @Context('client') client: Client,
    @Args('name', { nullable: false }) name: string,
    @Args('logo', { nullable: true }) logo?: string,
  ): Promise<Apparatus> {
    if (!client.isMaster()) throw new HttpException('Access denied', 403);

    const neu = await this.service.insert(client, { name, logo });

    pubsub.publish('ApparatusUpdated', { ApparatusUpdated: neu });

    return neu;
  }

  @Mutation(() => UUID, { nullable: false })
  async ApparatusDelete(
    @Context('client') client: Client,
    @Args('id', { type: () => UUID, nullable: false }) id: UUID
  ): Promise<UUID> {
    if (!client.isMaster()) throw new HttpException('Access denied', 403);

    this.service.delete(client, id);

    pubsub.publish('ApparatusDeleted', { ApparatusDeleted: id });

    return id;
  }
}
