import { Controller, Get, UseGuards, Patch, Body } from '@nestjs/common';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { CurrentUser } from '../auth/decorators/current-user.decorator';
import { User } from '../../entities/user.entity';
import { UsersService } from './users.service';
import { GoogleAuthService } from '../auth/google-auth.service';

@Controller('api/users')
export class UsersController {
  constructor(
    private readonly usersService: UsersService,
    private readonly googleAuthService: GoogleAuthService,
  ) {}

  @Get('me')
  @UseGuards(JwtAuthGuard)
  async me(@CurrentUser() user: User) {
    const { accessToken, refreshToken, tokenExpiry, ...profile } = user;
    const effectiveSettings = await this.usersService.getEffectiveSettings(user);
    
    // Check if Google Drive access is valid
    const hasValidGoogleAccess = !!(refreshToken && tokenExpiry);
    const tokenExpiryDate = tokenExpiry ? new Date(tokenExpiry * 1000) : null;
    const isTokenExpired = tokenExpiry ? tokenExpiry < Math.floor(Date.now() / 1000) : true;
    
    return { 
      ...profile, 
      effectiveSettings,
      googleDrive: {
        hasAccess: hasValidGoogleAccess,
        tokenExpiry: tokenExpiryDate,
        isExpired: isTokenExpired,
        needsReauth: !hasValidGoogleAccess || !refreshToken,
      }
    };
  }

  @Get('check-drive-access')
  @UseGuards(JwtAuthGuard)
  async checkDriveAccess(@CurrentUser() user: User) {
    try {
      // Attempt to get a valid access token (will refresh if needed)
      await this.googleAuthService.getValidAccessToken(user);
      return { 
        valid: true, 
        message: 'Google Drive access is valid' 
      };
    } catch (error: any) {
      const needsReauth = 
        error.message.includes('No refresh token') ||
        error.message.includes('must re-authenticate') ||
        error.message.includes('expired or revoked');
      
      return { 
        valid: false, 
        needsReauth,
        message: error.message || 'Google Drive access check failed'
      };
    }
  }

  @Patch('me')
  @UseGuards(JwtAuthGuard)
  async updateMe(
    @CurrentUser() user: User,
    @Body('name') name?: string,
    @Body('showUploaderInfo') showUploaderInfo?: boolean,
  ) {
    const updated = await this.usersService.updateUser(user.id, { name, showUploaderInfo });
    const { accessToken, refreshToken, tokenExpiry, ...profile } = updated;
    return profile;
  }
}
