import type { DataSource } from 'typeorm';
import type { IAvatarGenerationRepository } from '@core/media/domain/repositories/IAvatarGenerationRepository';
import type { AvatarGenerationRequest } from '@core/media/domain/entities/AvatarGenerationRequest';
import { AvatarGenerationRequestOrmEntity } from '../entities/AvatarGenerationRequestOrmEntity';
import { AvatarGenerationRequestOrmMapper } from '../mappers/AvatarGenerationRequestOrmMapper';

export class TypeOrmAvatarGenerationRepository implements IAvatarGenerationRepository {
  constructor(
    private readonly dataSource: DataSource,
    private readonly mapper: AvatarGenerationRequestOrmMapper,
  ) {}

  async save(request: AvatarGenerationRequest): Promise<void> {
    const repo = this.dataSource.getRepository(AvatarGenerationRequestOrmEntity);
    const entity = this.mapper.toOrmEntity(request);
    await repo.save(entity);
  }

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

  async findByUserId(userId: string): Promise<AvatarGenerationRequest[]> {
    const repo = this.dataSource.getRepository(AvatarGenerationRequestOrmEntity);
    const entities = await repo.find({ 
      where: { userId },
      order: { createdAt: 'DESC' }
    });
    return entities.map(entity => this.mapper.toDomain(entity));
  }

  async findLatestByUserId(userId: string): Promise<AvatarGenerationRequest | null> {
    const repo = this.dataSource.getRepository(AvatarGenerationRequestOrmEntity);
    const entity = await repo.findOne({ 
      where: { userId },
      order: { createdAt: 'DESC' }
    });
    return entity ? this.mapper.toDomain(entity) : null;
  }

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