import type { Avatar } from '@core/media/domain/entities/Avatar';
import type { AvatarRepository } from '@core/media/domain/repositories/AvatarRepository';
import type { DataSource } from 'typeorm';
import { AvatarOrmEntity } from '../entities/AvatarOrmEntity';
import { AvatarOrmMapper } from '../mappers/AvatarOrmMapper';

export class TypeOrmAvatarRepository implements AvatarRepository {
  constructor(
    private readonly dataSource: DataSource,
    private readonly mapper: AvatarOrmMapper,
  ) {}

  async save(avatar: Avatar): Promise<void> {
    const repo = this.dataSource.getRepository(AvatarOrmEntity);
    const entity = this.mapper.toOrmEntity(avatar);
    await repo.save(entity);
  }

  async findById(id: string): Promise<Avatar | null> {
    const repo = this.dataSource.getRepository(AvatarOrmEntity);
    const entity = await repo.findOne({ where: { id } });
    return entity ? this.mapper.toDomain(entity) : null;
  }

  async findActiveByDriverId(driverId: string): Promise<Avatar | null> {
    const repo = this.dataSource.getRepository(AvatarOrmEntity);
    const entity = await repo.findOne({ 
      where: { driverId, isActive: true },
      order: { selectedAt: 'DESC' }
    });
    return entity ? this.mapper.toDomain(entity) : null;
  }

  async findByDriverId(driverId: string): Promise<Avatar[]> {
    const repo = this.dataSource.getRepository(AvatarOrmEntity);
    const entities = await repo.find({ 
      where: { driverId },
      order: { selectedAt: 'DESC' }
    });
    return entities.map(entity => this.mapper.toDomain(entity));
  }

  async delete(id: string): Promise<void> {
    const repo = this.dataSource.getRepository(AvatarOrmEntity);
    await repo.delete({ id });
  }
}
