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

@Injectable()
export class EducationLevelsService {
  constructor(
    @InjectRepository(EducationLevels)
    private readonly educationLevelsRepository: Repository<EducationLevels>,
  ) {}

  async findAll(): Promise<EducationLevels[]> {
    return this.educationLevelsRepository.find({ where: { status: 1 } });
  }

  async search(query: string) {
    const q = `%${query || ''}%`;
    return this.educationLevelsRepository.query(
      `SELECT * FROM education_levels WHERE status = 1 AND LOWER(name) LIKE LOWER(?) ORDER BY name ASC LIMIT 10`,
      [q],
    );
  }

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

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

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

  async create(body: any): Promise<any> {
    const educationLevel = this.educationLevelsRepository.create(body);
    return this.educationLevelsRepository.save(educationLevel);
  }

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

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