// PÚBLICO — sin JWT: la tablet de ingreso vinculada. El código de la tablet va en
// el cuerpo (CORS no admite otro header); la base guarda sólo su hash. Rate limit
// por IP: la tablet del gimnasio está en una sola IP y no hace falta más.
import { Body, Controller, HttpCode, HttpStatus, Post, Res, UseGuards } from '@nestjs/common';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { Throttle, ThrottlerGuard } from '@nestjs/throttler';
import type { Response } from 'express';
import { SkipSuscripcionCheck } from 'src/common/guards/suscripcion.guard';
import { IngresoTabletDto, TabletDto } from './dto/tablet.dto';
import { TabletsGymService } from './tablets-gym.service';

@ApiTags('Gimnasio · Público')
@Throttle({ default: { limit: 60, ttl: 60_000 } })
@UseGuards(ThrottlerGuard)
@SkipSuscripcionCheck()
@Controller({ path: 'gimnasio-publico/tablet', version: '1' })
export class TabletPublicoController {
  constructor(private readonly tablets: TabletsGymService) {}

  @Post('info')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: 'Gimnasio y sede de la tablet vinculada (410 si la desvincularon)' })
  info(@Body() dto: TabletDto) {
    return this.tablets.info(dto.k);
  }

  @Post('logo')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: 'Logo del gimnasio para la cabecera de la tablet (404 si la empresa no cargó uno)' })
  // La imagen pasa por acá y no se da su URL: la del bucket lleva el id de la empresa (regla 10).
  // res.send directo: el BigIntSerializerInterceptor global serializaría el Buffer como JSON.
  async logo(@Body() dto: TabletDto, @Res() res: Response): Promise<void> {
    const { contenido, tipo } = await this.tablets.logo(dto.k);
    res.set({ 'Content-Type': tipo, 'Cache-Control': 'private, max-age=3600' });
    res.send(contenido);
  }

  @Post('ingreso')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: 'El socio escribe su CI en la tablet y entra (mismas reglas que recepción)' })
  ingreso(@Body() dto: IngresoTabletDto) {
    return this.tablets.ingreso(dto);
  }
}
