import { ForbiddenException, Inject } from '@nestjs/common';
import { type ICommandHandler, CommandHandler } from '@nestjs/cqrs';
import { NotFoundException } from '@modules/shared';
import {
  PROJECT_REPOSITORY,
  type IProjectRepository,
} from '../../../domain/repositories/project-development.repository';
import { DeleteProjectCommand } from './delete-project.command';

@CommandHandler(DeleteProjectCommand)
export class DeleteProjectHandler implements ICommandHandler<DeleteProjectCommand> {
  constructor(
    @Inject(PROJECT_REPOSITORY)
    private readonly repo: IProjectRepository,
  ) {}

  async execute(cmd: DeleteProjectCommand): Promise<void> {
    const entity = await this.repo.findById(cmd.id);
    if (!entity) {
      throw new NotFoundException('Dự án', cmd.id);
    }

    // Authorisation: ADMIN may delete anything; DEVELOPER may delete only
    // projects they own.
    if (cmd.requesterRole !== 'ADMIN') {
      if (cmd.requesterRole !== 'DEVELOPER' || entity.ownerId !== cmd.requesterUserId) {
        throw new ForbiddenException('Bạn không có quyền xoá dự án này');
      }
    }

    await this.repo.delete(cmd.id);
  }
}
