import {
  Controller,
  Post,
  Get,
  Body,
  Res,
  Req,
  UseGuards,
  HttpCode,
  HttpStatus,
  UnauthorizedException,
} from '@nestjs/common';
import { Throttle } from '@nestjs/throttler';
import { Response, Request } from 'express';
import { AuthService } from './auth.service';
import { AuthGuard } from './guards/auth.guard';
import { SetSessionDto } from './dto/set-session.dto';
import { User } from '../user/user.entity';

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

  @Post('session')
  @HttpCode(HttpStatus.OK)
  @Throttle({ default: { ttl: 60_000, limit: 10 } })
  async setSession(
    @Body() dto: SetSessionDto,
    @Res({ passthrough: true }) res: Response,
  ) {
    return this.authService.setSession(dto, res);
  }

  @Post('refresh')
  @HttpCode(HttpStatus.OK)
  @Throttle({ default: { ttl: 60_000, limit: 10 } })
  async refresh(
    @Req() req: Request,
    @Res({ passthrough: true }) res: Response,
  ) {
    const refreshToken = (req.signedCookies as Record<string, string>)?.refresh_token;
    if (!refreshToken) {
      throw new UnauthorizedException('Pas de refresh token');
    }
    return this.authService.refreshSession(res, refreshToken);
  }

  @Get('me')
  @UseGuards(AuthGuard)
  async getMe(@Req() req: Request & { user: User }) {
    return this.authService.getMe(req.user);
  }

  @Post('logout')
  @HttpCode(HttpStatus.NO_CONTENT)
  logout(@Res({ passthrough: true }) res: Response) {
    this.authService.logout(res);
  }
}
