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

@Injectable()
export class SavedCandidatesService {
  constructor(
    @InjectRepository(SavedCandidate)
    private savedCandidateRepository: Repository<SavedCandidate>,
  ) {}

  async create(data: any): Promise<SavedCandidate> {
    const savedCandidate = this.savedCandidateRepository.create(data);
    const result = await this.savedCandidateRepository.save(savedCandidate);
    return Array.isArray(result) ? result[0] : result;
  }

  async findAll(): Promise<SavedCandidate[]> {
    return await this.savedCandidateRepository
      .createQueryBuilder('saved')
      .where('saved.is_deleted = :isDeleted', { isDeleted: false })
      .getMany();
  }

  async findOne(id: number): Promise<SavedCandidate | null> {
    return await this.savedCandidateRepository
      .createQueryBuilder('saved')
      .where('saved.id = :id', { id })
      .andWhere('saved.is_deleted = :isDeleted', { isDeleted: false })
      .getOne();
  }

  async findByRecruiterId(recruiterId: number): Promise<SavedCandidate[]> {
    return await this.savedCandidateRepository
      .createQueryBuilder('saved')
      .where('saved.recruiter_id = :recruiterId', { recruiterId })
      .andWhere('saved.is_deleted = :isDeleted', { isDeleted: false })
      .getMany();
  }

  async findByAssociateId(associateId: number): Promise<SavedCandidate[]> {
    return await this.savedCandidateRepository
      .createQueryBuilder('saved')
      .where('saved.associate_id = :associateId', { associateId })
      .andWhere('saved.is_deleted = :isDeleted', { isDeleted: false })
      .getMany();
  }

  async update(id: number, data: any): Promise<void> {
    await this.savedCandidateRepository
      .createQueryBuilder()
      .update(SavedCandidate)
      .set(data)
      .where('id = :id', { id })
      .execute();
  }

  async remove(id: number): Promise<void> {
    await this.savedCandidateRepository
      .createQueryBuilder()
      .update(SavedCandidate)
      .set({ is_deleted: true })
      .where('id = :id', { id })
      .execute();
  }
}
