import { Injectable, Logger } from '@nestjs/common';
import { CreateLogDto } from './dto/create-log.dto';
import { UpdateLogDto } from './dto/update-log.dto';
import { PrismaService } from 'src/prisma/prisma.service';

@Injectable()
export class LogsService {
	constructor(private prisma: PrismaService) {}
	private readonly logger = new Logger(LogsService.name);

	create(createLogDto: CreateLogDto) {
		return this.prisma.log.create({ data: createLogDto });
	}

	findAll(skip = 0, take = 10, sortBy: string, sortOrder: string, search: string = '', type: string = 'system', typeId: number = 0) {
		const transaction = this.prisma.$transaction(async (tx) => {
			this.logger.log({ level: 'info', message: 'Returning all logs', refCode: '21202' });
			if (take < 0) {
				take = 100;
			}
			let searchID = parseInt(search);

			if (Number.isNaN(searchID)) {
				searchID = 0;
			}

			var logs = await tx.log.findManyAndCount({
				skip,
				take,
				orderBy: {
					[sortBy]: sortOrder,
				},
				where: {
					AND: [
						{ type: type },
						{ typeId: typeId },
						{
							OR: [{ id: { equals: searchID } }, { level: { contains: search } }, { message: { contains: search } }],
						},
					],
				},
			});
			return logs;
		});
		return transaction;
	}

	findOne(id: number) {
		return `This action returns a #${id} log`;
	}

	findByJobId(jobId: string) {
		const transaction = this.prisma.$transaction(async (tx) => {
			this.logger.log({ level: 'info', message: 'Returning all logs for jobId: ' + jobId, refCode: '21202' });

			var logs = await tx.log.findMany({
				where: {
					type: 'job',
					typeId: parseInt(jobId),
				},
				orderBy: {
					timestamp: 'desc',
				},
			});
			return logs;
		});
		return transaction;
	}

	update(id: number, updateLogDto: UpdateLogDto) {
		return `This action updates a #${id} log`;
	}

	remove(id: number) {
		return `This action removes a #${id} log`;
	}
}
