import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ApiResponseLog } from './entities/api-response-log.entity';

@Injectable()
export class ApiResponseLogService {
  private readonly logger = new Logger(ApiResponseLogService.name);

  constructor(
    @InjectRepository(ApiResponseLog)
    private readonly logRepository: Repository<ApiResponseLog>,
  ) {}

  async store(data: { source: string | null; message: any }): Promise<ApiResponseLog> {
    const log = this.logRepository.create({
      source: data.source,
      message: data.message,
    });
    return await this.logRepository.save(log);
  }

  async findOne(id: number): Promise<ApiResponseLog | null> {
    return await this.logRepository.findOne({ where: { id } });
  }

  async findAll(page: number = 1, limit: number = 20): Promise<{ data: ApiResponseLog[]; total: number; page: number; limit: number }> {
    const [data, total] = await this.logRepository.findAndCount({
      order: { created_at: 'DESC' },
      skip: (page - 1) * limit,
      take: limit,
    });
    return { data, total, page, limit };
  }
}
