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

@Injectable()
export class JobAlertsService {
  constructor(
    @InjectRepository(JobAlert)
    private jobAlertRepository: Repository<JobAlert>,
  ) {}

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

  async findAll(): Promise<JobAlert[]> {
    return this.jobAlertRepository.createQueryBuilder('alert').getMany();
  }

  async findOne(id: number): Promise<JobAlert | null> {
    return await this.jobAlertRepository
      .createQueryBuilder('alert')
      .where('alert.id = :id', { id })
      .getOne();
  }

  async findByUserId(userId: number): Promise<JobAlert[]> {
    return await this.jobAlertRepository
      .createQueryBuilder('alert')
      .where('alert.user_id = :userId', { userId })
      .andWhere('alert.is_active = :isActive', { isActive: true })
      .getMany();
  }

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

  async remove(id: number): Promise<void> {
    await this.jobAlertRepository
      .createQueryBuilder()
      .delete()
      .from(JobAlert)
      .where('id = :id', { id })
      .execute();
  }
}
