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

@Injectable()
export class JobTypeService {
  constructor(
    @InjectRepository(JobType)
    private readonly jobTypeRepository: Repository<JobType>,
  ) {}

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

  async search(query: string) {
    const q = `%${query || ''}%`;
    return this.jobTypeRepository.query(
      `SELECT * FROM job_type 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.jobTypeRepository.findAndCount({
      skip,
      take: limit,
      order: { id: 'ASC' },
    });

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

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

  async create(data: Partial<JobType>): Promise<JobType> {
    const jobType = this.jobTypeRepository.create(data);
    return this.jobTypeRepository.save(jobType);
  }

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

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