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

const configService = new ConfigService;

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

    const allowType = [
      'image/jpg',
      'image/jpeg',
      'image/png',
      'image/gif',
    ]
    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();
  }
}