import { Injectable, NestInterceptor, ExecutionContext, CallHandler, HttpException } from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap, catchError } from 'rxjs/operators';
import * as fs from 'fs';
import * as path from 'path';

@Injectable()
export class RequestLoggerInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const req = context.switchToHttp().getRequest();
    const method = req.method;
    const url = req.url;
    const timestamp = new Date().toISOString();

    const logEntry = `[${timestamp}] Incoming Request: ${method} ${url}\nHeaders: ${JSON.stringify(req.headers)}\nQuery: ${JSON.stringify(req.query)}\nBody: ${JSON.stringify(req.body)}\nUser: ${JSON.stringify(req.user)}\n\n`;
    
    try {
        fs.appendFileSync(path.join(process.cwd(), 'API_REQUEST_LOG.txt'), logEntry);
    } catch (e) {}

    return next.handle().pipe(
      tap(() => {
        const res = context.switchToHttp().getResponse();
        const successLog = `[${new Date().toISOString()}] Response: ${method} ${url} -> ${res.statusCode}\n\n`;
        try { fs.appendFileSync(path.join(process.cwd(), 'API_REQUEST_LOG.txt'), successLog); } catch (e) {}
      }),
      catchError((error) => {
        const status = error instanceof HttpException ? error.getStatus() : 500;
        const errorLog = `[${new Date().toISOString()}] Error Response: ${method} ${url} -> ${status}\nMessage: ${error.message}\nStack: ${error.stack}\n\n`;
        try { fs.appendFileSync(path.join(process.cwd(), 'API_REQUEST_LOG.txt'), errorLog); } catch (e) {}
        throw error;
      })
    );
  }
}
