import {
  BadRequestException,
  HttpStatus,
  Injectable,
  NotFoundException,
} from '@nestjs/common';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Config } from '../entities/configs.entity';
import AppResponse from '@/response/app-response';

@Injectable()
export class ConfigsService {
  public static CONFIG_KEYS = {
    REFRESH_TOOL_TIME: 'REFRESH_TOOL_TIME',
    MAIL_SCRAP_REPORT: 'MAIL_SCRAP_REPORT',
  };

  constructor(
    @InjectRepository(Config)
    readonly configRepo: Repository<Config>,
  ) {}

  async getConfig(key_name: keyof typeof ConfigsService.CONFIG_KEYS) {
    return (await this.configRepo.findOne({ where: { key_name } })) || null;
  }

  async setConfig(
    key_name: keyof typeof ConfigsService.CONFIG_KEYS,
    value: string,
    type: 'string' | 'number',
  ) {
    return await this.configRepo.upsert({ key_name, value, type }, [
      'key_name',
    ]);
  }

  async getConfigRes(key_name: string) {
    const result = await this.getConfig(
      key_name as keyof typeof ConfigsService.CONFIG_KEYS,
    );

    if (!result)
      throw new NotFoundException(
        AppResponse.toResponse(null, {
          message: 'Config key name not found',
          status_code: HttpStatus.NOT_FOUND,
        }),
      );

    return AppResponse.toResponse(result);
  }

  async upsertConfig(data: Partial<Config>) {
    let response = null;

    const prevConfig = await this.configRepo.findOne({
      where: { key_name: data.key_name },
    });

    if (!prevConfig) {
      response = await this.configRepo.save(data);
    } else {
      response = await this.configRepo.update(
        { key_name: data.key_name },
        data,
      );
    }

    if (!response) throw new BadRequestException(AppResponse.toResponse(false));

    return AppResponse.toResponse(!!response);
  }
}
