import { Body, Controller, Get, HttpCode, HttpStatus, Patch, Post, Query, Req, Res, UseGuards } from '@nestjs/common';
import { Throttle } from '@nestjs/throttler';
import { CookieOptions, Request, Response } from 'express';
import { AuthService } from './auth.service';
import { LoginDto } from './dto/login.dto';
import { ForgotPasswordDto } from './dto/forgot-password.dto';
import { ResetPasswordDto } from './dto/reset-password.dto';
import { AcceptInviteDto } from './dto/accept-invite.dto';
import { UpdateProfileDto } from './dto/update-profile.dto';
import { ChangePasswordDto } from './dto/change-password.dto';
import { RequestResetLinkDto } from './dto/request-reset-link.dto';
import { JwtAuthGuard } from '../../common/auth/jwt-auth.guard';
import { CurrentUser } from '../../common/auth/current-user.decorator';

const SESSION_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000; // 7 days

function getCookieBaseOptions(httpOnly: boolean): CookieOptions {
  const secure = process.env.COOKIE_SECURE !== undefined ? process.env.COOKIE_SECURE === 'true' : process.env.NODE_ENV === 'production';

  return {
    httpOnly,
    secure,
    sameSite: 'lax',
    path: '/',
  };
}

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

  private getAuthCookieName(): string {
    const isSecure = process.env.COOKIE_SECURE !== undefined ? process.env.COOKIE_SECURE === 'true' : process.env.NODE_ENV === 'production';
    return isSecure ? '__Host-tcx_token' : 'tcx_token';
  }

  private setSessionCookies(res: Response, accessToken: string) {
    const cookieName = this.getAuthCookieName();
    res.cookie(cookieName, accessToken, {
      ...getCookieBaseOptions(true),
      maxAge: SESSION_MAX_AGE_MS,
    });
    // If switching to __Host- cookie in secure mode, clean up legacy cookie
    if (cookieName !== 'tcx_token') {
      res.clearCookie('tcx_token', { path: '/' });
    }
    res.cookie('tcx_session', '1', {
      ...getCookieBaseOptions(false),
      maxAge: SESSION_MAX_AGE_MS,
    });
  }

  private clearSessionCookies(res: Response) {
    res.clearCookie('__Host-tcx_token', getCookieBaseOptions(true));
    res.clearCookie('tcx_token', getCookieBaseOptions(true));
    res.clearCookie('tcx_session', getCookieBaseOptions(false));
  }

  // Authenticates user and issues session token. POST /api/auth/login
  @Post('login')
  @Throttle({ default: { limit: 20, ttl: 60000 } })
  @HttpCode(HttpStatus.OK)
  async login(@Body() dto: LoginDto, @Req() req: Request, @Res({ passthrough: true }) res: Response) {
    const ipAddress = req.ip || req.socket.remoteAddress;
    const result = await this.authService.login(dto, ipAddress);
    this.setSessionCookies(res, result.accessToken);
    return result;
  }

  // Logs out user and clears session cookies. POST /api/auth/logout
  @Post('logout')
  @HttpCode(HttpStatus.OK)
  async logout(@Req() req: Request, @Res({ passthrough: true }) res: Response) {
    const cookieToken = req.cookies?.['__Host-tcx_token'] || req.cookies?.tcx_token;
    const authHeader = req.headers.authorization;
    const bearerToken = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : null;
    const token = cookieToken || bearerToken;
    if (token) {
      await this.authService.revokeSession(token);
    }
    this.clearSessionCookies(res);
    return { success: true, message: 'Logged out successfully' };
  }

  // Returns current authenticated user profile. GET /api/auth/me
  @Get('me')
  @UseGuards(JwtAuthGuard)
  async getMe(@CurrentUser('id') userId: string) {
    return this.authService.getMe(userId);
  }

  // Updates current user profile details. PATCH /api/auth/profile
  @Patch('profile')
  @UseGuards(JwtAuthGuard)
  @HttpCode(HttpStatus.OK)
  async updateProfile(@CurrentUser('id') userId: string, @Body() dto: UpdateProfileDto) {
    return this.authService.updateProfile(userId, dto);
  }

  // Changes password for authenticated user. POST /api/auth/change-password
  @Post('change-password')
  @UseGuards(JwtAuthGuard)
  @HttpCode(HttpStatus.OK)
  async changePassword(@CurrentUser('id') userId: string, @Body() dto: ChangePasswordDto) {
    return this.authService.changePassword(userId, dto);
  }

  // Sends password reset link to user email after verifying current password. POST /api/auth/send-reset-link
  @Post('send-reset-link')
  @Throttle({ default: { limit: 20, ttl: 60000 } })
  @UseGuards(JwtAuthGuard)
  @HttpCode(HttpStatus.OK)
  async sendResetLink(@CurrentUser('id') userId: string, @Body() dto: RequestResetLinkDto) {
    return this.authService.sendResetLinkWithPassword(userId, dto);
  }

  // Initiates password reset request via email. POST /api/auth/forgot-password
  @Post('forgot-password')
  @Throttle({ default: { limit: 20, ttl: 60000 } })
  @HttpCode(HttpStatus.OK)
  async forgotPassword(@Body() dto: ForgotPasswordDto) {
    return this.authService.forgotPassword(dto);
  }

  // Completes password reset using token. POST /api/auth/reset-password
  @Post('reset-password')
  @HttpCode(HttpStatus.OK)
  async resetPassword(@Body() dto: ResetPasswordDto) {
    return this.authService.resetPassword(dto);
  }

  // Retrieves invitation metadata for pre-filling accept invite page. GET /api/auth/invite-info
  @Get('invite-info')
  async getInviteInfo(@Query('token') token: string) {
    return this.authService.getInviteInfo(token);
  }

  // Accepts member invitation and sets password. POST /api/auth/accept-invite
  @Post('accept-invite')
  @HttpCode(HttpStatus.OK)
  async acceptInvite(@Body() dto: AcceptInviteDto, @Res({ passthrough: true }) res: Response) {
    const result = await this.authService.acceptInvite(dto);
    this.setSessionCookies(res, result.accessToken);
    return result;
  }
}
