import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
  Logger,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { Request } from 'express';

/**
 * 로깅 인터셉터 - Docker 환경에서 로그 출력 보장
 */
@Injectable()
export class LoggingInterceptor implements NestInterceptor {
  private readonly logger = new Logger('HTTP');

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const request = context.switchToHttp().getRequest<Request>();
    const { method, url, ip } = request;
    const userAgent = request.get('user-agent') || '';
    const now = Date.now();

    const incomingLog = `[REQUEST] ${method} ${url} - IP: ${ip}`;
    this.logger.log(incomingLog);
    process.stdout.write(`${new Date().toISOString()} - ${incomingLog}\n`);

    return next.handle().pipe(
      tap({
        next: () => {
          const responseTime = Date.now() - now;
          const successLog = `[RESPONSE] ${method} ${url} - ${responseTime}ms - SUCCESS`;
          this.logger.log(successLog);
          process.stdout.write(`${new Date().toISOString()} - ${successLog}\n`);
        },
        error: (error) => {
          const responseTime = Date.now() - now;
          const errorLog = `[RESPONSE] ${method} ${url} - ${responseTime}ms - ERROR: ${error.message}`;
          this.logger.error(errorLog);
          process.stdout.write(`${new Date().toISOString()} - ${errorLog}\n`);
        },
      }),
    );
  }
}
