import AppResponse from '@/response/app-response';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { plainToClass } from 'class-transformer';
import { IsNull, Not, Repository } from 'typeorm';
import { CreateScrapConfigDto } from '../dto/scrap-config/create-scrap-config';
import { UpdateScrapConfigDto } from '../dto/scrap-config/update-scrap-config';
import { ScrapConfig } from '../entities/scrap-config.entity';

@Injectable()
export class ScrapConfigsService {
  constructor(
    @InjectRepository(ScrapConfig)
    readonly scrapConfigRepo: Repository<ScrapConfig>,
  ) {}

  async clientGetScrapeConfigs() {
    const data = await this.scrapConfigRepo.find({
      where: {
        search_url: Not(IsNull()),
        keywords: Not(IsNull()),
        enable: true,
      },
      relations: {
        web_bid: true,
      },
    });

    return AppResponse.toResponse(plainToClass(ScrapConfig, data));
  }

  async create(data: CreateScrapConfigDto) {
    const result = await this.scrapConfigRepo.save({
      search_url: data.search_url,
      keywords: data.keywords,
      web_bid: { id: data.web_id },
    });

    if (!result) return AppResponse.toResponse(false);

    return AppResponse.toResponse(true);
  }

  async update(
    id: ScrapConfig['id'],
    { web_id, ...data }: UpdateScrapConfigDto,
  ) {
    const result = await this.scrapConfigRepo.update(id, { ...data });

    if (!result.affected) return AppResponse.toResponse(false);

    return AppResponse.toResponse(true);
  }
}
