import { Injectable, NotFoundException, ConflictException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Country } from './entities/country.entity';
import { CreateCountryDto } from './dto/create-country.dto';
import { UpdateCountryDto } from './dto/update-country.dto';

@Injectable()
export class CountriesService {
  constructor(
    @InjectRepository(Country, 'scheme_dbs')
    private readonly countryRepository: Repository<Country>,
  ) {}

  async create(createCountryDto: CreateCountryDto) {
    const exists = await this.countryRepository.findOneBy({ code: createCountryDto.code });
    if (exists) throw new ConflictException('Country with this code already exists');

    const country = this.countryRepository.create(createCountryDto);
    return this.countryRepository.save(country);
  }

  findAll() {
    return this.countryRepository.find({ order: { name: 'ASC' } });
  }

  async findOne(id: number) {
    const country = await this.countryRepository.findOneBy({ id });
    if (!country) throw new NotFoundException(`Country with id ${id} not found`);
    return country;
  }

  async update(id: number, updateCountryDto: UpdateCountryDto) {
    const country = await this.countryRepository.findOneBy({ id });
    if (!country) throw new NotFoundException(`Country with id ${id} not found`);

    if (updateCountryDto.code) {
      const duplicate = await this.countryRepository.findOneBy({ code: updateCountryDto.code });
      if (duplicate && duplicate.id !== id)
        throw new ConflictException('Another country with this code already exists');
    }

    await this.countryRepository.update(id, updateCountryDto);
    return this.countryRepository.findOneBy({ id });
  }

  async remove(id: number) {
    const result = await this.countryRepository.softDelete(id);
    if (result.affected === 0) throw new NotFoundException(`Country with id ${id} not found`);
    return { message: 'Country deleted successfully', id };
  }
}
