import { Injectable, Inject, Logger } from '@nestjs/common';
import { DeviceToken, DevicePlatform, PushChannel } from '../../domain/entities/device-token.entity';
import {
  DEVICE_TOKEN_REPOSITORY,
  IDeviceTokenRepository,
} from '../../domain/repositories/device-token.repository.interface';

export interface RegisterTokenParams {
  userId: string;
  platform: DevicePlatform;
  channel: PushChannel;
  token: string;
  deviceId?: string;
  deviceModel?: string;
  appVersion?: string;
}

@Injectable()
export class DeviceTokenService {
  private readonly logger = new Logger(DeviceTokenService.name);

  constructor(
    @Inject(DEVICE_TOKEN_REPOSITORY)
    private readonly deviceTokenRepo: IDeviceTokenRepository,
  ) {}

  async registerToken(params: RegisterTokenParams): Promise<DeviceToken> {
    const saved = await this.deviceTokenRepo.upsertToken({
      userId: params.userId,
      platform: params.platform,
      channel: params.channel,
      token: params.token,
      deviceId: params.deviceId ?? null,
      deviceModel: params.deviceModel ?? null,
      appVersion: params.appVersion ?? null,
    });
    this.logger.log(
      `Device token registered: user=${params.userId} channel=${params.channel} platform=${params.platform}`,
    );
    return saved;
  }

  async unregisterToken(token: string): Promise<void> {
    await this.deviceTokenRepo.deactivateToken(token);
    this.logger.log(`Device token unregistered: ${token.slice(0, 12)}…`);
  }

  async unregisterAllForUser(userId: string): Promise<void> {
    await this.deviceTokenRepo.deactivateAllForUser(userId);
    this.logger.log(`All device tokens deactivated for user ${userId}`);
  }

  async getActiveTokens(userId: string): Promise<DeviceToken[]> {
    return this.deviceTokenRepo.findActiveByUserId(userId);
  }

  async getChannelStats(): Promise<Array<{ channel: PushChannel; count: number }>> {
    return this.deviceTokenRepo.countByChannel();
  }
}
