import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { Observable } from 'rxjs';
import { FileService } from './file.service';
import { UserAccessDTO } from './dto/user-access-dto';
import { ApiError } from '../common/error/api-error';
import { ApiErrorCodes } from '../common/error/api-error-codes';
import { diskStorage } from 'multer';
import { ConfigService } from '@nestjs/config';
import * as fs from 'fs';

@Injectable()
export class FileUploadLogicInterceptor implements NestInterceptor {
  constructor(
    private readonly fileService: FileService,
    private readonly configService: ConfigService,
  ) {}

  async intercept(
    context: ExecutionContext,
    next: CallHandler,
  ): Promise<Observable<any>> {
    const request = context.switchToHttp().getRequest();
    const user = request.user as UserAccessDTO;
    if (!user) {
      throw new ApiError('You must be logged in', ApiErrorCodes.ACCESS_DENIED);
    }

    const access = await this.fileService.checkUploadStore(
      user,
      request.params.store,
      request.params.dir ?? null,
    );

    const temp_dir = this.configService.get('server.tempDir');

    await fs.promises.mkdir(temp_dir, {
      recursive: true,
    });

    const interceptor = new (FileInterceptor('file', {
      limits: {
        fileSize: Number(access.limit),
      },
      storage: diskStorage({
        destination: temp_dir,
        filename: function (req, file, cb) {
          const uniqueSuffix =
            Date.now() + '-' + Math.round(Math.random() * 1e9);
          cb(null, uniqueSuffix);
        },
      }),
    }))();
    return await interceptor.intercept(context, next);
  }
}
