import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { JobCategories } from './entities/job_categories.entity';

@Injectable()
export class JobCategoriesService {
  constructor(
    @InjectRepository(JobCategories)
    private readonly jobCategoriesRepo: Repository<JobCategories>,
  ) {}

  async findAll(): Promise<JobCategories[]> {
    return this.jobCategoriesRepo.find();
  }

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

  async findOne(id: number): Promise<JobCategories> {
    const category = await this.jobCategoriesRepo.findOne({ where: { id } });
    if (!category) throw new NotFoundException('Job category not found');
    return category;
  }

  async create(data: Partial<JobCategories>): Promise<JobCategories> {
    const newCategory = this.jobCategoriesRepo.create(data);
    return this.jobCategoriesRepo.save(newCategory);
  }

  async update(
    id: number,
    data: Partial<JobCategories>,
  ): Promise<JobCategories> {
    const category = await this.findOne(id);
    Object.assign(category, data);
    return this.jobCategoriesRepo.save(category);
  }

  async remove(id: number): Promise<{ message: string }> {
    const category = await this.findOne(id);
    await this.jobCategoriesRepo.remove(category);
    return { message: 'Job category deleted successfully' };
  }
}
