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

@Injectable()
export class LanguagesService {
  constructor(
    @InjectRepository(Languages)
    private languagesRepository: Repository<Languages>,
  ) {}

  findAll(): Promise<Languages[]> {
    return this.languagesRepository.find({
      where: { status: 1 },
      order: { name: 'ASC' },
    });
  }

  async findAllPaginated(page: number = 1, limit: number = 10) {
    const skip = (page - 1) * limit;
    const [data, total] = await this.languagesRepository.findAndCount({
      skip,
      take: limit,
      order: { name: 'ASC' }, // Assuming name sort
    });

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

  async findOne(id: number): Promise<Languages> {
    return this.languagesRepository.findOne({ where: { id } });
  }

  async create(createLanguagesDto: any): Promise<any> {
    const newLanguage = this.languagesRepository.create(createLanguagesDto);
    return this.languagesRepository.save(newLanguage);
  }

  async update(id: number, updateLanguagesDto: any): Promise<any> {
    await this.languagesRepository.update(id, updateLanguagesDto);
    return this.languagesRepository.findOne({ where: { id } });
  }

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