import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Country } from './entities/country.entity';

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

  // Fetch all records from country table
  async findAll() {
    return this.countryRepository
      .createQueryBuilder('c')
      .where('c.status = :status', { status: 1 })
      .orderBy('c.country_id', 'ASC')
      .getMany();
  }
  async findAllPaginated(
    page: number = 1,
    limit: number = 10,
    status?: number,
  ) {
    const skip = (page - 1) * limit;
    const where: any = {};
    if (status !== undefined) where.status = status;

    const [data, total] = await this.countryRepository.findAndCount({
      where,
      skip,
      take: limit,
      order: { country_name: 'ASC' },
    });

    return {
      success: true,
      data,
      meta: {
        totalItems: total,
        itemsPerPage: limit,
        currentPage: page,
        totalPages: Math.ceil(total / limit),
      },
    };
  }

  async findOne(id: number): Promise<Country> {
    return this.countryRepository.findOne({ where: { country_id: id } });
  }

  async create(createCountryDto: any): Promise<any> {
    const newCountry = this.countryRepository.create(createCountryDto);
    return this.countryRepository.save(newCountry);
  }

  async update(id: number, updateCountryDto: any): Promise<any> {
    delete updateCountryDto.id;
    await this.countryRepository.update({ country_id: id }, updateCountryDto);
    return this.countryRepository.findOne({ where: { country_id: id } });
  }

  async remove(id: number): Promise<void> {
    await this.countryRepository.delete({ country_id: id });
  }
}
