//this interceptor is used to not save the media files in case of any error occurred

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

@Injectable()
export class FileValidationInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      catchError((error) => {
        const request = context.switchToHttp().getRequest();

        if (error instanceof HttpException) {
          const response = error.getResponse();
          const code = response['code'];

          if (code !== 200 || code !== 201) {
            // Delete files if code is not equal to 200 or 201
            if (request.files) {
              this.deleteFiles(request.files);
            }
          }
        }
        throw error;
      }),
    );
  }

  deleteFiles(files: any) {
    // Delete uploaded files
    for (const key in files) {
      if (Array.isArray(files[key])) {
        for (const file of files[key]) {
          if (typeof file === 'object' && file && 'path' in file) {
            fs.unlink(file.path, () => {});
          }
        }
      } else {
        const file = files[key];

        if (typeof file === 'object' && file && 'path' in file) {
          fs.unlink(file.path, () => {});
        }
      }
    }
  }
}
