import { BadRequestException, Injectable } from '@nestjs/common';
import { RegisterDeviceDto } from './dto/register-device.dto';
import { UnregisterDeviceDto } from './dto/unregister-device.dto';
import { DevicesRepository } from './devices.repository';

@Injectable()
export class DevicesService {
  constructor(private readonly devicesRepository: DevicesRepository) {}

  async register(userId: string, dto: RegisterDeviceDto) {
    const fcmToken = dto.fcmToken.trim();
    if (!fcmToken) {
      throw new BadRequestException('fcmToken is required');
    }

    const device = await this.devicesRepository.upsert(userId, {
      fcmToken,
      platform: dto.platform,
      deviceId: dto.deviceId?.trim() ?? '',
      appVersion: dto.appVersion?.trim() ?? '',
      locale: dto.locale?.trim() ?? '',
    });

    return {
      message: 'Device registered successfully',
      device,
    };
  }

  async unregister(userId: string, dto: UnregisterDeviceDto) {
    if (!dto.deviceId?.trim() && !dto.fcmToken?.trim()) {
      throw new BadRequestException('deviceId or fcmToken is required');
    }

    const device = await this.devicesRepository.deactivate(userId, {
      deviceId: dto.deviceId?.trim(),
      fcmToken: dto.fcmToken?.trim(),
    });

    return {
      message: 'Device unregistered successfully',
      device,
    };
  }
}
