import { Body, Controller, Post } from '@nestjs/common';
import { Throttle } from '@nestjs/throttler';
import { z } from 'zod';
import { AuthService } from './auth.service';

/** Five a minute in production; roomier elsewhere, where one IP is everybody. */
const LOGIN_ATTEMPTS_PER_MINUTE = process.env.NODE_ENV === 'production' ? 5 : 50;

const loginSchema = z.object({
  email: z.string().email(),
  password: z.string().min(1),
});

const refreshSchema = z.object({ refreshToken: z.string().min(1) });

@Controller('auth')
export class AuthController {
  constructor(private readonly auth: AuthService) {}

  // Tight limit on the unauthenticated login route to blunt credential stuffing
  // (login also runs a synchronous scrypt). Five a minute per IP in production;
  // outside it the whole team, the browser and any test script share one address,
  // so the same ceiling locks a developer out of their own machine. The
  // production number is the one that matters and it is unchanged.
  @Throttle({ default: { limit: LOGIN_ATTEMPTS_PER_MINUTE, ttl: 60_000 } })
  @Post('login')
  async login(@Body() body: unknown) {
    const { email, password } = loginSchema.parse(body);
    return this.auth.login(email, password);
  }

  // Also rate-limited: it is unauthenticated in the same sense login is, and a
  // stolen refresh token should not be usable as an oracle at full speed.
  @Throttle({ default: { limit: LOGIN_ATTEMPTS_PER_MINUTE, ttl: 60_000 } })
  @Post('refresh')
  async refresh(@Body() body: unknown) {
    const { refreshToken } = refreshSchema.parse(body);
    return this.auth.refresh(refreshToken);
  }
}
