import { query, queryOne } from '../../config/database.js';
import { NotFoundError } from '../../shared/errors/index.js';

export interface Country {
  id: string;
  code: string;
  name: string;
  phone_code?: string;
  currency_code?: string;
  created_at: Date;
}

class CountriesService {
  async findAll(): Promise<Country[]> {
    return query<Country>(
      `SELECT * FROM core.countries ORDER BY name`
    );
  }

  async findById(id: string): Promise<Country> {
    const country = await queryOne<Country>(
      `SELECT * FROM core.countries WHERE id = $1`,
      [id]
    );
    if (!country) {
      throw new NotFoundError('País no encontrado');
    }
    return country;
  }

  async findByCode(code: string): Promise<Country | null> {
    return queryOne<Country>(
      `SELECT * FROM core.countries WHERE code = $1`,
      [code.toUpperCase()]
    );
  }
}

export const countriesService = new CountriesService();
