import { v4 as uuidv4 } from 'uuid';
import { Device } from '../../../domain/entities/device';
import { IDeviceRepository } from '../../../domain/repositories/device-repository';
import { CreateDeviceInput } from '../../dto/device.dto';

export class CreateDeviceUseCase {
  constructor(private readonly deviceRepository: IDeviceRepository) {}

  async execute(input: CreateDeviceInput): Promise<Device> {
    const existing = await this.deviceRepository.findByFingerprint(input.fingerprint);
    if (existing) {
      const pushToken = input.pushToken ?? null;
      if (pushToken && existing.pushToken !== pushToken) {
        const updated = existing.updatePushToken(pushToken);
        return this.deviceRepository.update(updated);
      }
      return existing;
    }

    const device = Device.create(
      uuidv4(),
      input.location,
      input.type,
      input.info ?? null,
      input.ipAddress,
      input.userAgent ?? null,
      input.fingerprint,
      input.status,
      input.pushToken ?? null,
    );

    return this.deviceRepository.save(device);
  }
}
