import { Injectable } from '@nestjs/common';
import { DataSource, Repository } from 'typeorm';
import { PoolServer } from '../../domain/entities/pool-server.entity';

@Injectable()
export class PoolServerRepository {
  private readonly repo: Repository<PoolServer>;

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

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

  findAvailable(): Promise<PoolServer[]> {
    return this.repo
      .createQueryBuilder('ps')
      .where('ps.status = :status', { status: 'active' })
      .andWhere('ps.current_instances < ps.max_instances')
      .orderBy('ps.current_instances', 'ASC')
      .getMany();
  }

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

  save(server: PoolServer): Promise<PoolServer> {
    return this.repo.save(server);
  }

  async remove(server: PoolServer): Promise<void> {
    await this.repo.remove(server);
  }

  async incrementInstances(id: string): Promise<void> {
    await this.repo.increment({ id }, 'currentInstances', 1);
  }

  async decrementInstances(id: string): Promise<void> {
    await this.repo
      .createQueryBuilder()
      .update(PoolServer)
      .set({ currentInstances: () => 'GREATEST(current_instances - 1, 0)' })
      .where('id = :id', { id })
      .execute();
  }
}
