import { Injectable } from '@nestjs/common';
import { DataSource } from 'typeorm';
import { TenantAwareRepository } from '@it0/database';
import { AgentInstance } from '../../domain/entities/agent-instance.entity';

@Injectable()
export class AgentInstanceRepository extends TenantAwareRepository<AgentInstance> {
  constructor(dataSource: DataSource) {
    super(dataSource, AgentInstance);
  }

  findAll(): Promise<AgentInstance[]> {
    return this.withRepository((repo) =>
      repo.find({ order: { createdAt: 'DESC' } }),
    );
  }

  findById(id: string): Promise<AgentInstance | null> {
    return this.withRepository((repo) =>
      repo.findOne({ where: { id } as any }),
    );
  }

  findByUserId(userId: string): Promise<AgentInstance[]> {
    return this.withRepository((repo) =>
      repo.find({ where: { userId } as any, order: { createdAt: 'DESC' } }),
    );
  }

  findByPoolServer(poolServerId: string): Promise<AgentInstance[]> {
    return this.withRepository((repo) =>
      repo.find({ where: { poolServerId, status: 'running' } as any }),
    );
  }

  async save(instance: AgentInstance): Promise<AgentInstance> {
    return this.withRepository((repo) => repo.save(instance));
  }

  // Get all host ports in use on a specific server (across all tenants via public query)
  async getUsedPortsOnServer(dataSource: DataSource, serverHost: string): Promise<number[]> {
    const rows = await dataSource.query(
      `SELECT host_port FROM agent_instances WHERE server_host = $1 AND status != 'removed'`,
      [serverHost],
    );
    return rows.map((r: any) => r.host_port as number);
  }
}
