import { Injectable, NotFoundException } from '@nestjs/common';
import { MqttClientService } from '../ingest/mqtt-client.service';
import { PrismaService } from '../prisma/prisma.service';
import { SimPublishPointDto } from './dto/sim.dto';

@Injectable()
export class SimService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly mqttClient: MqttClientService,
  ) {}

  // Publishes onto the real broker rather than writing to the DB directly, so
  // the simulator exercises the exact same ingest path a real locator would.
  async publish(orgId: string, dto: SimPublishPointDto) {
    const job = await this.prisma.job.findFirst({ where: { id: dto.jobId, orgId }, select: { id: true } });
    if (!job) {
      throw new NotFoundException('Job not found in this organization');
    }

    const { serial, ...payload } = dto;
    this.mqttClient.publish(`devices/${serial}/log`, payload);
    return { ok: true, topic: `devices/${serial}/log` };
  }
}
