import { Repository } from 'typeorm';
import { IDeviceRepository } from '../../../domain/repositories/device-repository';
import { PaginationOptions } from '../../../domain/repositories/pagination-options';
import { Device } from '../../../domain/entities/device';
import { DeviceEntity } from '../entities/device.entity';
import { AppDataSource } from '../data-source';
import { deviceMapper } from './mappers/device.mapper';

export class TypeOrmDeviceRepository implements IDeviceRepository {
  private get repository(): Repository<DeviceEntity> {
    return AppDataSource.getRepository(DeviceEntity);
  }

  async findById(id: string): Promise<Device | null> {
    const entity = await this.repository.findOneBy({ id });
    return entity ? deviceMapper.toDomain(entity) : null;
  }

  async findByFingerprint(fingerprint: string): Promise<Device | null> {
    const entity = await this.repository.findOneBy({ fingerprint });
    return entity ? deviceMapper.toDomain(entity) : null;
  }

  async findAll(options?: PaginationOptions): Promise<Device[]> {
    const entities = await this.repository.find({
      take: options?.limit,
      skip: options?.offset,
      order: { createdAt: 'DESC' },
    });
    return entities.map(deviceMapper.toDomain);
  }

  async save(device: Device): Promise<Device> {
    const entity = await this.repository.save(deviceMapper.toEntity(device));
    return deviceMapper.toDomain(entity);
  }

  async update(device: Device): Promise<Device> {
    const entity = await this.repository.save(deviceMapper.toEntity(device));
    return deviceMapper.toDomain(entity);
  }

  async delete(id: string): Promise<void> {
    await this.repository.delete(id);
  }
}
