// company-suggestions.service.ts
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, ILike } from 'typeorm';
import { CompanySuggestions } from './entities/company_suggestions.entity';

@Injectable()
export class CompanySuggestionsService {
  constructor(
    @InjectRepository(CompanySuggestions)
    private readonly companyRepo: Repository<CompanySuggestions>,
  ) {}

  async suggestCompanies(
    query: string,
  ): Promise<Partial<CompanySuggestions>[]> {
    if (!query || query.trim() === '') return [];

    try {
      return this.companyRepo.find({
        select: ['id', 'name', 'cin'], // return only id + name for autocomplete
        where: { name: ILike(`${query}%`), status: 'Active' },
        take: 10,
        order: { name: 'ASC' },
      });
    } catch (error) {
      console.error(' Error in suggestCompanies:', error);
      return [];
    }
  }

  async findAllPaginated(page: number = 1, limit: number = 10) {
    const skip = (page - 1) * limit;

    const query = this.companyRepo
      .createQueryBuilder('cs')
      .leftJoinAndSelect('state', 's', 's.state_id = cs.state_id')
      .leftJoinAndSelect(
        'organization_types',
        'ot',
        'ot.id = cs.organization_type_id',
      )
      .select([
        'cs.*',
        's.state_name AS state_name',
        'ot.label AS organization_type_label',
      ])
      .orderBy('cs.name', 'ASC')
      .offset(skip)
      .limit(limit);

    const data = await query.getRawMany();
    const total = await this.companyRepo.count();

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

  async create(createDto: any) {
    const newItem = this.companyRepo.create(createDto);
    return this.companyRepo.save(newItem);
  }

  async update(id: number, updateDto: any) {
    // Remove non-entity fields that might be present from the frontend
    const { state_name, organization_type_label, ...validData } = updateDto;
    return this.companyRepo.update(id, validData);
  }

  async remove(id: number) {
    return this.companyRepo.delete(id);
  }
}
