import { Controller, Get, Post, Body, Query, Res, Redirect, HttpStatus } from '@nestjs/common';
import { Response } from 'express';
import { AuthService } from './AuthService';
import { LoginParams, SignupParams, LoginWithIracingCallbackParams } from './dto/AuthDto';

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

  @Post('signup')
  async signup(@Body() params: SignupParams) {
    return this.authService.signupWithEmail(params);
  }

  @Post('login')
  async login(@Body() params: LoginParams) {
    return this.authService.loginWithEmail(params);
  }

  @Get('session')
  async getSession() {
    return this.authService.getCurrentSession();
  }

  @Post('logout')
  async logout() {
    return this.authService.logout();
  }

  @Get('iracing/start')
  async startIracingAuthRedirect(@Query('returnTo') returnTo?: string, @Res() res?: Response) {
    const { redirectUrl, state } = await this.authService.startIracingAuthRedirect(returnTo);
    // In real application, you might want to store 'state' in a secure cookie or session.
    // For this example, we'll just redirect.
    res.redirect(HttpStatus.FOUND, redirectUrl);
  }

  @Get('iracing/callback')
  async loginWithIracingCallback(@Query('code') code: string, @Query('state') state: string, @Query('returnTo') returnTo?: string) {
    return this.authService.loginWithIracingCallback({ code, state, returnTo });
  }
}
