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

@Injectable()
export class AgentInstanceRepository {
  private readonly repo: Repository<AgentInstance>;

  constructor(private readonly dataSource: DataSource) {
    this.repo = dataSource.getRepository(AgentInstance);
  }

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

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

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

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

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

  // Get all host ports in use on a specific server
  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);
  }
}
