import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Dispute } from '../../domain/entities/dispute.entity';
import { IDisputeRepository } from '../../domain/repositories/dispute.repository.interface';

@Injectable()
export class DisputeRepository implements IDisputeRepository {
  constructor(
    @InjectRepository(Dispute)
    private readonly repo: Repository<Dispute>,
  ) {}

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

  async save(dispute: Dispute): Promise<Dispute> {
    return this.repo.save(dispute);
  }

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

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

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

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

    return qb.getManyAndCount();
  }
}
