import { Injectable, Inject } from '@nestjs/common';
import { GetMyDevicesQuery } from './get-my-devices.query';
import {
  UserAccountRepository,
  USER_ACCOUNT_REPOSITORY,
} from '@/domain/repositories/user-account.repository.interface';
import { UserId } from '@/domain/value-objects';
import { ApplicationError } from '@/shared/exceptions/domain.exception';
import { DeviceDTO } from '@/application/commands';

@Injectable()
export class GetMyDevicesHandler {
  constructor(
    @Inject(USER_ACCOUNT_REPOSITORY)
    private readonly userRepository: UserAccountRepository,
  ) {}

  async execute(query: GetMyDevicesQuery): Promise<DeviceDTO[]> {
    const account = await this.userRepository.findById(
      UserId.create(query.userId),
    );
    if (!account) throw new ApplicationError('用户不存在');

    return account.getAllDevices().map((device) => ({
      deviceId: device.deviceId,
      deviceName: device.deviceName,
      addedAt: device.addedAt,
      lastActiveAt: device.lastActiveAt,
      isCurrent: device.deviceId === query.currentDeviceId,
    }));
  }
}
