import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Report, ReportType } from '../../domain/entities/report.entity';
import { IReportRepository } from '../../domain/repositories/report.repository.interface';

@Injectable()
export class ReportRepository implements IReportRepository {
  constructor(
    @InjectRepository(Report)
    private readonly repo: Repository<Report>,
  ) {}

  async findById(id: string): Promise<Report | null> {
    return this.repo.findOne({ where: { id } });
  }

  async findAndCount(options: {
    type?: ReportType;
    page: number;
    limit: number;
  }): Promise<[Report[], number]> {
    const qb = this.repo.createQueryBuilder('r');

    if (options.type) {
      qb.where('r.type = :type', { type: options.type });
    }

    qb.orderBy('r.created_at', 'DESC')
      .skip((options.page - 1) * options.limit)
      .take(options.limit);

    return qb.getManyAndCount();
  }

  create(data: Partial<Report>): Report {
    return this.repo.create(data);
  }

  async save(report: Report): Promise<Report> {
    return this.repo.save(report);
  }
}
