import { Body, Controller, Param, Post, UseGuards } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { ThrottlerGuard } from '@nestjs/throttler';
import { RedeemMqttChallengeDto } from './dto/device-mqtt-auth.dto';
import { DeviceMqttAuthService } from './device-mqtt-auth.service';

// Public and unauthenticated by design, same trust model as
// DeviceStatusController: a BLE-only locator has no login of its own, only
// its permanent certificate. Throttled (unlike DeviceStatusController) since
// each request here does real work — an openssl signature verification and,
// on success, a fresh cert issuance — rather than a single indexed read.
@ApiTags('device-mqtt-auth (public)')
@Controller('devices/:serial/mqtt-session')
@UseGuards(ThrottlerGuard)
export class DeviceMqttAuthController {
  constructor(private readonly deviceMqttAuth: DeviceMqttAuthService) {}

  @Post('challenge')
  challenge(@Param('serial') serial: string) {
    return this.deviceMqttAuth.issueChallenge(serial);
  }

  @Post()
  redeem(@Param('serial') serial: string, @Body() dto: RedeemMqttChallengeDto) {
    return this.deviceMqttAuth.redeemChallenge(serial, dto.nonce, dto.signature);
  }
}
