import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { IDeviceProfileRepository } from '../../../domain/repositories/device-profile.repository.interface';
import { DeviceProfile } from '../../../domain/entities/device-profile.entity';

@Injectable()
export class DeviceProfileRepositoryImpl implements IDeviceProfileRepository {
  constructor(private readonly prisma: PrismaService) {}

  async upsertBatch(profiles: DeviceProfile[]): Promise<void> {
    if (profiles.length === 0) return;

    // 同一批次中同一 install_id 可能重复，取最后一条
    const map = new Map<string, DeviceProfile>();
    for (const p of profiles) {
      map.set(p.installId, p);
    }
    const unique = Array.from(map.values());

    // 使用原生 SQL 实现高效 upsert:
    // ON CONFLICT (install_id) DO UPDATE
    //   - 覆盖设备字段（始终更新为最新值）
    //   - last_seen_at 更新为当前时间
    //   - event_count 累加
    const now = new Date();
    for (const p of unique) {
      await this.prisma.$executeRaw`
        INSERT INTO analytics_device_profile
          (install_id, user_id, device_brand, device_model, device_os, app_version, locale,
           first_seen_at, last_seen_at, event_count)
        VALUES
          (${p.installId}, ${p.userId}, ${p.deviceBrand}, ${p.deviceModel},
           ${p.deviceOs}, ${p.appVersion}, ${p.locale}, ${now}, ${now}, ${p.eventCount})
        ON CONFLICT (install_id) DO UPDATE SET
          user_id      = COALESCE(EXCLUDED.user_id, analytics_device_profile.user_id),
          device_brand = COALESCE(EXCLUDED.device_brand, analytics_device_profile.device_brand),
          device_model = COALESCE(EXCLUDED.device_model, analytics_device_profile.device_model),
          device_os    = COALESCE(EXCLUDED.device_os, analytics_device_profile.device_os),
          app_version  = COALESCE(EXCLUDED.app_version, analytics_device_profile.app_version),
          locale       = COALESCE(EXCLUDED.locale, analytics_device_profile.locale),
          last_seen_at = ${now},
          event_count  = analytics_device_profile.event_count + ${p.eventCount}
      `;
    }
  }
}
