import type { DataSource } from 'typeorm';

import type { IUserRatingRepository } from '@core/identity/domain/repositories/IUserRatingRepository';
import type { UserRating } from '@core/identity/domain/value-objects/UserRating';

import { UserRatingOrmEntity } from '../entities/UserRatingOrmEntity';
import { UserRatingOrmMapper } from '../mappers/UserRatingOrmMapper';

/**
 * TypeORM Implementation: IUserRatingRepository
 * 
 * Persists and retrieves UserRating snapshots for fast reads.
 */
export class TypeOrmUserRatingRepository implements IUserRatingRepository {
  constructor(private readonly dataSource: DataSource) {}

  async findByUserId(userId: string): Promise<UserRating | null> {
    const repo = this.dataSource.getRepository(UserRatingOrmEntity);
    const entity = await repo.findOne({ where: { userId } });
    
    if (!entity) {
      return null;
    }
    
    return UserRatingOrmMapper.toDomain(entity);
  }

  async save(userRating: UserRating): Promise<UserRating> {
    const repo = this.dataSource.getRepository(UserRatingOrmEntity);
    const entity = UserRatingOrmMapper.toOrmEntity(userRating);
    await repo.save(entity);
    return userRating;
  }
}