import { PrismaService } from 'src/database/prisma.service';
import { AbilityAction } from '../ability.action';
import { AppAbility } from '../ability.factory';
import { IAbilityHandler } from '../interfaces/ability-handler.interface';
import {
  ExecutionContext,
  Injectable,
  NotFoundException,
} from '@nestjs/common';
import { CommentThreadTargetWhereInput } from 'src/core/@generated/comment-thread-target/comment-thread-target-where.input';
import { GqlExecutionContext } from '@nestjs/graphql';
import { assert } from 'src/utils/assert';
import { subject } from '@casl/ability';

class CommentThreadTargetArgs {
  where?: CommentThreadTargetWhereInput;
}

@Injectable()
export class ManageCommentThreadTargetAbilityHandler
  implements IAbilityHandler
{
  async handle(ability: AppAbility) {
    return ability.can(AbilityAction.Manage, 'CommentThreadTarget');
  }
}

@Injectable()
export class ReadCommentThreadTargetAbilityHandler implements IAbilityHandler {
  handle(ability: AppAbility) {
    return ability.can(AbilityAction.Read, 'CommentThreadTarget');
  }
}

@Injectable()
export class CreateCommentThreadTargetAbilityHandler
  implements IAbilityHandler
{
  handle(ability: AppAbility) {
    return ability.can(AbilityAction.Create, 'CommentThreadTarget');
  }
}

@Injectable()
export class UpdateCommentThreadTargetAbilityHandler
  implements IAbilityHandler
{
  constructor(private readonly prismaService: PrismaService) {}

  async handle(ability: AppAbility, context: ExecutionContext) {
    const gqlContext = GqlExecutionContext.create(context);
    const args = gqlContext.getArgs<CommentThreadTargetArgs>();
    const commentThreadTarget =
      await this.prismaService.commentThreadTarget.findFirst({
        where: args.where,
      });
    assert(commentThreadTarget, '', NotFoundException);

    return ability.can(
      AbilityAction.Update,
      subject('CommentThreadTarget', commentThreadTarget),
    );
  }
}

@Injectable()
export class DeleteCommentThreadTargetAbilityHandler
  implements IAbilityHandler
{
  constructor(private readonly prismaService: PrismaService) {}

  async handle(ability: AppAbility, context: ExecutionContext) {
    const gqlContext = GqlExecutionContext.create(context);
    const args = gqlContext.getArgs<CommentThreadTargetArgs>();
    const commentThreadTarget =
      await this.prismaService.commentThreadTarget.findFirst({
        where: args.where,
      });
    assert(commentThreadTarget, '', NotFoundException);

    return ability.can(
      AbilityAction.Delete,
      subject('CommentThreadTarget', commentThreadTarget),
    );
  }
}
