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

@Injectable()
export class IndustriesService {
  constructor(
    @InjectRepository(Industries)
    private readonly industriesRepository: Repository<Industries>,
  ) {}

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

  async search(query: string) {
    const q = `%${query || ''}%`;
    return this.industriesRepository.query(
      `SELECT * FROM industries 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.industriesRepository.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<Industries | null> {
    return this.industriesRepository.findOne({ where: { id } });
  }

  async create(createIndustryDto: any): Promise<Industries> {
    const industry = this.industriesRepository.create(
      createIndustryDto,
    ) as unknown as Industries;
    return this.industriesRepository.save(industry);
  }

  async update(id: number, updateIndustryDto: any): Promise<Industries | null> {
    await this.industriesRepository.update(id, updateIndustryDto);
    return this.findOne(id);
  }

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