import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { SarReport } from '../../domain/entities/sar-report.entity';
import { ISarReportRepository } from '../../domain/repositories/sar-report.repository.interface';

@Injectable()
export class SarReportRepository implements ISarReportRepository {
  constructor(
    @InjectRepository(SarReport)
    private readonly repo: Repository<SarReport>,
  ) {}

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

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

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

  async update(id: string, data: Partial<SarReport>): Promise<void> {
    await this.repo.update(id, data);
  }

  async count(options?: { where?: Record<string, any> }): Promise<number> {
    return this.repo.count(options);
  }

  async findPaginated(
    page: number,
    limit: number,
    filters?: { status?: string },
  ): Promise<[SarReport[], number]> {
    const qb = this.repo.createQueryBuilder('sar');

    if (filters?.status) {
      qb.andWhere('sar.filing_status = :status', { status: filters.status });
    }

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

    return qb.getManyAndCount();
  }
}
