import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { AuditLog } from '../../domain/entities/audit-log.entity';
import { IAuditLogRepository } from '../../domain/repositories/audit-log.repository.interface';

@Injectable()
export class AuditLogRepository implements IAuditLogRepository {
  constructor(
    @InjectRepository(AuditLog)
    private readonly repo: Repository<AuditLog>,
  ) {}

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

  async save(log: AuditLog): Promise<AuditLog> {
    return this.repo.save(log);
  }

  async findPaginated(
    page: number,
    limit: number,
    filters?: {
      action?: string;
      adminId?: string;
      resource?: string;
      startDate?: string;
      endDate?: string;
    },
  ): Promise<[AuditLog[], number]> {
    const qb = this.repo.createQueryBuilder('log');

    if (filters?.action) {
      qb.andWhere('log.action = :action', { action: filters.action });
    }
    if (filters?.adminId) {
      qb.andWhere('log.admin_id = :adminId', { adminId: filters.adminId });
    }
    if (filters?.resource) {
      qb.andWhere('log.resource = :resource', { resource: filters.resource });
    }
    if (filters?.startDate) {
      qb.andWhere('log.created_at >= :startDate', { startDate: filters.startDate });
    }
    if (filters?.endDate) {
      qb.andWhere('log.created_at <= :endDate', { endDate: filters.endDate });
    }

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

    return qb.getManyAndCount();
  }
}
