import { CallHandler, ExecutionContext, mixin, NestInterceptor, Type } from '@nestjs/common';
import FastifyMulter from 'fastify-multer';
import { Observable } from 'rxjs';
import { Options } from 'fastify-multer/lib/interfaces';

export function FastifyFileInterceptor(
  fieldName: string,
  localOptions?: Options,
): Type<NestInterceptor> {
  class MixinInterceptor implements NestInterceptor {
    protected multer: any;

    constructor() {
      this.multer = FastifyMulter(localOptions);
    }

    async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<any>> {
      const ctx = context.switchToHttp();

      await new Promise<void>((resolve, reject) =>
        this.multer.single(fieldName)(
          ctx.getRequest(),
          ctx.getResponse(),
          (error: any) => {
            if (error) {
              reject(error);
            }
            resolve();
          },
        ),
      );

      return next.handle();
    }
  }
  const Interceptor = mixin(MixinInterceptor);
  return Interceptor;
}
