import { Injectable } from '@nestjs/common';
import { HealthIndicatorResult, HealthIndicator, HealthCheckError } from '@nestjs/terminus';
import { WorkspacePrismaPool } from '../workspace/workspace-prisma-pool.service';

// Amostra os K workspaces mais quentes do LRU — nunca O(N) sobre todos os workspaces.
// CODING-RULES §20 (PGD-OBS-003): readiness não percorre workspaces individualmente.

@Injectable()
export class WorkspacePoolHealthIndicator extends HealthIndicator {
  constructor(private readonly pool: WorkspacePrismaPool) {
    super();
  }

  async check(key = 'workspace_pool', k = 3): Promise<HealthIndicatorResult> {
    const results = await this.pool.health(k);

    if (results.length === 0) {
      return this.getStatus(key, true, { active: 0 });
    }

    const failed = results.filter((r) => !r.ok);
    const isHealthy = failed.length === 0;
    const detail = {
      active: results.length,
      healthy: results.length - failed.length,
      ...(failed.length > 0 && { failed: failed.map((r) => r.workspaceId) }),
    };

    if (!isHealthy) {
      throw new HealthCheckError(`${key} degradado`, this.getStatus(key, false, detail));
    }

    return this.getStatus(key, true, detail);
  }
}
