import type { DataSource } from 'typeorm';
import type { IMediaRepository } from '@core/media/domain/repositories/IMediaRepository';
import type { Media } from '@core/media/domain/entities/Media';
import { MediaOrmEntity } from '../entities/MediaOrmEntity';
import { MediaOrmMapper } from '../mappers/MediaOrmMapper';

export class TypeOrmMediaRepository implements IMediaRepository {
  constructor(
    private readonly dataSource: DataSource,
    private readonly mapper: MediaOrmMapper,
  ) {}

  async save(media: Media): Promise<void> {
    const repo = this.dataSource.getRepository(MediaOrmEntity);
    const entity = this.mapper.toOrmEntity(media);
    await repo.save(entity);
  }

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

  async findByUploadedBy(uploadedBy: string): Promise<Media[]> {
    const repo = this.dataSource.getRepository(MediaOrmEntity);
    const entities = await repo.find({ where: { uploadedBy } });
    return entities.map(entity => this.mapper.toDomain(entity));
  }

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