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

@Injectable()
export class SkillsService {
  constructor(
    @InjectRepository(Skills)
    private skillsRepository: Repository<Skills>,
  ) {}

  // Normalize skill name: trim and capitalize properly
  private normalizeSkillName(name: string): string {
    return name
      .trim()
      .split(' ')
      .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
      .join(' ');
  }

  // Get all skills
  findAll(): Promise<Skills[]> {
    return this.skillsRepository.find({
      where: { is_active: true },
      order: { skill_name: 'ASC' },
    });
  }

  // Find skill by name (case-insensitive, trimmed)
  async findByName(skillName: string): Promise<Skills | null> {
    const trimmedName = skillName.trim();
    return this.skillsRepository
      .createQueryBuilder('skill')
      .where('LOWER(TRIM(skill.skill_name)) = LOWER(:skillName)', {
        skillName: trimmedName,
      })
      .getOne();
  }

  // Create a new skill
  async create(
    skillName: string,
    skillType: 'tech' | 'nontech' = 'tech',
  ): Promise<Skills> {
    const normalizedName = this.normalizeSkillName(skillName);
    const skill = this.skillsRepository.create({
      skill_name: normalizedName,
      skill_type: skillType,
      is_active: true,
    });
    return this.skillsRepository.save(skill);
  }

  // Create skill if it doesn't exist, otherwise return existing
  async createIfNotExists(
    skillName: string,
    skillType: 'tech' | 'nontech' = 'tech',
  ): Promise<Skills> {
    const existingSkill = await this.findByName(skillName);
    if (existingSkill) {
      return existingSkill;
    }
    return this.create(skillName, skillType);
  }

  // Get skills by IDs
  async findByIds(ids: number[]): Promise<Skills[]> {
    return this.skillsRepository.findByIds(ids);
  }
  async findByType(
    type: 'tech' | 'nontech',
    page: number = 1,
    limit: number = 10,
  ) {
    const skip = (page - 1) * limit;
    const [data, total] = await this.skillsRepository.findAndCount({
      where: { skill_type: type },
      skip,
      take: limit,
      order: { skill_name: 'ASC' },
    });

    return {
      success: true,
      data,
      meta: {
        totalItems: total,
        itemsPerPage: limit,
        currentPage: page,
        totalPages: Math.ceil(total / limit),
      },
    };
  }
  async update(id: number, updateDto: any): Promise<any> {
    await this.skillsRepository.update(id, updateDto);
    return this.skillsRepository.findOne({ where: { id } });
  }

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