import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Blacklists } from './blacklist.entity';

@Injectable()
export class BlacklistService {
  constructor(
    @InjectRepository(Blacklists)
    private blacklistRepository: Repository<Blacklists>,
  ) {}

  async getAll(): Promise<any> {
    return this.blacklistRepository.find();
  }

  async getById(id: number): Promise<Blacklists> {
    const item = await this.blacklistRepository.findOneBy({ idBlacklists: id });
    if (!item) {
      throw new Error('Blacklist item not found');
    }
    return item;
  }

  async add(body: any): Promise<any> {
    const newItem = this.blacklistRepository.create(body);
    const data = this.blacklistRepository.save(newItem);
    return {
      message: 'blacklist added!',
      data: newItem,
    };
  }

  async update(id: number, body: any): Promise<Blacklists> {
    const item = await this.blacklistRepository.findOneBy({ idBlacklists: id });
    if (!item) {
      throw new Error('Blacklist item not found');
    }
    const updated = Object.assign(item, body);
    return this.blacklistRepository.save(updated);
  }
}
