import { BadRequestException, CallHandler, ExecutionContext, Injectable, NestInterceptor } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { Observable } from "rxjs";
import { mimetypeAny } from "src/common/mimetype";

const configService = new ConfigService;

@Injectable()
export class AnyFile implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const req = context.switchToHttp().getRequest();

    const allowType = mimetypeAny;
    if (!allowType.includes(req.file.mimetype)){
      throw new BadRequestException("Type file tidak");
    }

    if (req.file.size > configService.get("MAX_SIZE_UPLOAD")) {
      throw new BadRequestException("Ukuran file melebihi batas yang diijinkan.")
    }

    return next.handle();
  }
}
