import { Injectable, Logger } from '@nestjs/common';
import { Device } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';

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

  constructor(private readonly prisma: PrismaService) {}

  // Serial numbers are globally unique, so a bare serial identifies a locator
  // regardless of which org's data pipeline saw it first. Unknown serials are
  // auto-registered under the given org so field data is never dropped.
  async resolve(orgId: string, serial: string): Promise<Device> {
    const existing = await this.prisma.device.findUnique({ where: { serialNumber: serial } });
    if (existing) {
      this.prisma.device
        .update({ where: { id: existing.id }, data: { lastSeenAt: new Date() } })
        .catch(() => undefined);
      return existing;
    }

    this.logger.log(`Auto-registering locator serial ${serial} under org ${orgId}`);
    try {
      return await this.prisma.device.create({
        data: { orgId, name: `Locator ${serial}`, serialNumber: serial, lastSeenAt: new Date() },
      });
    } catch {
      // lost a concurrent-registration race; the row exists now
      const raced = await this.prisma.device.findUnique({ where: { serialNumber: serial } });
      if (!raced) {
        throw new Error(`Failed to resolve or create locator ${serial}`);
      }
      return raced;
    }
  }
}
