import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { EntityManager, Repository } from 'typeorm';
import { CreateLogDTO } from './dto/create-log.dto';
import { LogEntry } from './entities/log-entry.entity';
import { LOGEVENT } from './model/logging-event.type';

@Injectable()
export class LoggingService {
  constructor(
    @InjectRepository(LogEntry)
    private repository: Repository<LogEntry>,
  ) {
    // void this.onStart();
  }

  private async onStart() {
    await this.repository.save({
      level: 'DEBUG',
      event: 'application_start',
      details: 'application started',
      userId: -1,
    });
  }

  async info(
    {
      event,
      details,
      userId,
    }: {
      event: LOGEVENT;
      details: string;
      userId: number;
    },
    manager?: EntityManager,
  ) {
    const e: CreateLogDTO = {
      event,
      details,
      userId,
      level: 'INFO',
    };
    await (manager?.getRepository(LogEntry) ?? this.repository).save(e);
  }

  async error({
    event,
    details,
    userId,
  }: {
    event: LOGEVENT;
    details: string;
    userId: number;
  }) {
    const e: CreateLogDTO = {
      event,
      details,
      userId,
      level: 'ERROR',
    };
    await this.repository.save(e);
  }

  async warn({
    event,
    details,
    userId,
  }: {
    event: LOGEVENT;
    details: string;
    userId: number;
  }) {
    const e: CreateLogDTO = {
      event,
      details,
      userId,
      level: 'WARN',
    };
    await this.repository.save(e);
  }

  async debug(data: {
    event: LOGEVENT;
    details: string;
    userId: number;
    duration?: number;
  }) {
    const e: CreateLogDTO = {
      event: data.event,
      details: data.details,
      userId: data.userId,
      level: 'DEBUG',
      duration: data.duration,
    };
    await this.repository.save(e);
  }
}
