import { Repository } from 'typeorm';
import { AppDataSource } from '../../config/typeorm.js';
import { Country } from './entities/country.entity.js';
import { NotFoundError } from '../../shared/errors/index.js';
import { logger } from '../../shared/utils/logger.js';

class CountriesService {
  private repository: Repository<Country>;

  constructor() {
    this.repository = AppDataSource.getRepository(Country);
  }

  async findAll(): Promise<Country[]> {
    logger.debug('Finding all countries');

    return this.repository.find({
      order: { name: 'ASC' },
    });
  }

  async findById(id: string): Promise<Country> {
    logger.debug('Finding country by id', { id });

    const country = await this.repository.findOne({
      where: { id },
    });

    if (!country) {
      throw new NotFoundError('País no encontrado');
    }

    return country;
  }

  async findByCode(code: string): Promise<Country | null> {
    logger.debug('Finding country by code', { code });

    return this.repository.findOne({
      where: { code: code.toUpperCase() },
    });
  }
}

export const countriesService = new CountriesService();
