import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { MoreThan, Repository } from 'typeorm';
import { AnonymousSession } from './anonymous-session.entity';

@Injectable()
export class AnonymousSessionsService {
  constructor(
    @InjectRepository(AnonymousSession)
    private readonly repo: Repository<AnonymousSession>,
  ) {}

  /**
   * Registers or refreshes a device session. Only non-identifying metadata
   * (platform, app version) should be supplied - see section 24.
   */
  async register(
    deviceId: string,
    metadata?: Record<string, any>,
  ): Promise<AnonymousSession> {
    const existing = await this.repo.findOne({ where: { deviceId } });
    if (existing) {
      if (metadata) existing.metadata = { ...(existing.metadata || {}), ...metadata };
      existing.lastSeen = new Date();
      return this.repo.save(existing);
    }
    return this.repo.save(this.repo.create({ deviceId, metadata }));
  }

  findByDeviceId(deviceId: string): Promise<AnonymousSession | null> {
    return this.repo.findOne({ where: { deviceId } });
  }

  /** "Active" = seen within the window, used by the admin dashboard. */
  countActiveSince(since: Date): Promise<number> {
    return this.repo.count({ where: { lastSeen: MoreThan(since) } });
  }

  count(): Promise<number> {
    return this.repo.count();
  }
}
