import { ForbiddenException, Inject } from '@nestjs/common';
import { type ICommandHandler, CommandHandler } from '@nestjs/cqrs';
import { NotFoundException } from '@modules/shared';
import {
  INDUSTRIAL_PARK_REPOSITORY,
  type IIndustrialParkRepository,
} from '../../../domain/repositories/industrial-park.repository';
import { DeleteIndustrialParkCommand } from './delete-industrial-park.command';

@CommandHandler(DeleteIndustrialParkCommand)
export class DeleteIndustrialParkHandler implements ICommandHandler<DeleteIndustrialParkCommand> {
  constructor(
    @Inject(INDUSTRIAL_PARK_REPOSITORY)
    private readonly repo: IIndustrialParkRepository,
  ) {}

  async execute(cmd: DeleteIndustrialParkCommand): Promise<void> {
    const entity = await this.repo.findById(cmd.id);
    if (!entity) {
      throw new NotFoundException('Khu công nghiệp', cmd.id);
    }

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

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