import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CreditMetric } from '../../domain/entities/credit-metric.entity';
import { ICreditMetricRepository } from '../../domain/repositories/credit-metric.repository.interface';

@Injectable()
export class CreditMetricRepository implements ICreditMetricRepository {
  constructor(
    @InjectRepository(CreditMetric)
    private readonly repo: Repository<CreditMetric>,
  ) {}

  async findLatestByIssuerId(issuerId: string): Promise<CreditMetric | null> {
    return this.repo.findOne({
      where: { issuerId },
      order: { calculatedAt: 'DESC' },
    });
  }

  async create(data: Partial<CreditMetric>): Promise<CreditMetric> {
    const entity = this.repo.create(data);
    return this.repo.save(entity);
  }

  async save(metric: CreditMetric): Promise<CreditMetric> {
    return this.repo.save(metric);
  }
}
