import { Controller, Get, Logger, Req, Res, UseGuards } from '@nestjs/common';
import { Response } from 'express';
import { ConfigService } from '@nestjs/config';
import { GoogleAuthGuard } from './guards/google-auth.guard';
import { AuthService } from './auth.service';

@Controller('api/auth')
export class AuthController {
  private readonly logger = new Logger(AuthController.name);

  constructor(
    private authService: AuthService,
    private config: ConfigService,
  ) { }

  @Get('google')
  @UseGuards(GoogleAuthGuard)
  async googleAuth() {
    // Guard redirects to Google
  }

  @Get('google/callback')
  @UseGuards(GoogleAuthGuard)
  async googleCallback(
    @Req() req: { user: import('./strategies/google.strategy').GoogleUserPayload },
    @Res() res: Response,
  ) {
    const frontendUrl = this.config.get('FRONTEND_URL', 'http://localhost:3000');
    try {
      const user = await this.authService.validateGoogleUser(req.user);
      if (!user.isActive) {
        // User exists but account is deactivated by admin
        return res.redirect(`${frontendUrl}/auth/callback?error=account_deactivated`);
      }
      const token = await this.authService.login(user);
      res.redirect(
        `${frontendUrl}/auth/callback?token=${encodeURIComponent(token)}`,
      );
    } catch (err: any) {
      this.logger.error('Google callback failed', err.stack || err.message);
      res.redirect(`${frontendUrl}/auth/callback?error=auth_failed`);
    }
  }
}
