import { Body, Controller, Get, HttpCode, Post, Req, Res, UseGuards } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { Throttle } from "@nestjs/throttler";
import { Request, Response } from "express";
import { AuthService } from "./auth.service";
import { LoginDto } from "./dto/login.dto";
import { JwtAuthGuard } from "./jwt-auth.guard";

@Controller("auth")
export class AuthController {
  constructor(
    private readonly auth: AuthService,
    private readonly config: ConfigService,
  ) {}

  // Brute-force guard: 5 attempts/minute per IP, well above any real admin
  // mistyping their password, far below what a credential-stuffing script
  // needs to be slowed to uselessness.
  @Throttle({ default: { limit: 5, ttl: 60_000 } })
  @Post("login")
  @HttpCode(200)
  async login(@Body() dto: LoginDto, @Res({ passthrough: true }) res: Response) {
    const user = await this.auth.validateCredentials(dto.email, dto.password);
    const { token, maxAgeMs } = this.auth.issueToken(user);

    res.cookie(this.config.get<string>("AUTH_COOKIE_NAME") ?? "infobahn_admin_token", token, {
      httpOnly: true,
      secure: this.config.get<string>("COOKIE_SECURE") === "true",
      sameSite: "lax",
      maxAge: maxAgeMs,
      path: "/",
    });

    return { id: user.id, email: user.email, name: user.name };
  }

  @Post("logout")
  @HttpCode(200)
  logout(@Res({ passthrough: true }) res: Response) {
    res.clearCookie(this.config.get<string>("AUTH_COOKIE_NAME") ?? "infobahn_admin_token", { path: "/" });
    return { ok: true };
  }

  @UseGuards(JwtAuthGuard)
  @Get("me")
  async me(@Req() req: Request) {
    const claims = req.user as { id: string; email: string };
    const user = await this.auth.findById(claims.id);
    if (!user) {
      return { authenticated: false };
    }
    return { authenticated: true, id: user.id, email: user.email, name: user.name };
  }
}
