import { RoleMappingRuleRepository } from '@n8n/db';
import { Service } from '@n8n/di';

import type { RoleDeletionChecker } from '@/services/role-deletion-check-proxy.service';

import { ProvisioningService } from './provisioning.service.ee';

/**
 * Blocks deletion of a custom role while it is still targeted by an SSO role
 * mapping rule or configured as the role mapping default condition.
 * Registered on the core `RoleDeletionCheckProxy` by the provisioning module
 * so `RoleService` stays decoupled from this module.
 */
@Service()
export class ProvisioningRoleDeletionChecker implements RoleDeletionChecker {
	constructor(
		private readonly roleMappingRuleRepository: RoleMappingRuleRepository,
		private readonly provisioningService: ProvisioningService,
	) {}

	async findRoleDeletionBlockers(roleSlug: string): Promise<string[]> {
		const blockers: string[] = [];

		const count = await this.roleMappingRuleRepository.count({
			where: { role: { slug: roleSlug } },
		});
		if (count > 0) {
			blockers.push(`referenced by ${count} role mapping rule${count === 1 ? '' : 's'}`);
		}

		const { defaultInstanceRole } = await this.provisioningService.getConfig();
		if (defaultInstanceRole === roleSlug) {
			blockers.push('configured as the role mapping default condition role');
		}

		return blockers;
	}
}
