import { AuthMethod, MultiTenancyInterceptor, UseAuth } from '@backend/auth'
import {
	Controller,
	FileTypeValidator,
	MaxFileSizeValidator,
	ParseFilePipe,
	Post,
	UploadedFile,
	UseInterceptors,
} from '@nestjs/common'
import {
	ApiBadRequestResponse,
	ApiBody,
	ApiConsumes,
	ApiForbiddenResponse,
	ApiInternalServerErrorResponse,
	ApiOkResponse,
	ApiTags,
} from '@nestjs/swagger'
import { StorageService } from '../services'
import { FileUploadRequest, FileUploadResponse } from '../types'
import { FileInterceptor, MulterFile } from 'nestjs-busboy'

@UseAuth(AuthMethod.JWT)
@UseInterceptors(MultiTenancyInterceptor)
@Controller('file')
@ApiTags('default')
export class storageController {
	constructor(private readonly _storageService: StorageService) {}

	@UseInterceptors(FileInterceptor('file'))
	@Post('upload')
	@ApiConsumes('multipart/form-data')
	@ApiBody({ type: FileUploadRequest })
	@ApiOkResponse({ type: FileUploadResponse })
	@ApiBadRequestResponse()
	@ApiForbiddenResponse()
	@ApiInternalServerErrorResponse()
	uploadFile(
		@UploadedFile(
			new ParseFilePipe({
				validators: [
					// Allow upto 5 mb image file
					new MaxFileSizeValidator({ maxSize: 5_000_000, errorMessage: 'File should be less than 5 mb' }),
					new FileTypeValidator({ fileType: /(^image)(\/)\w*/g }),
				],
			}),
		)
		file: MulterFile,
	): Promise<FileUploadResponse> {
		return this._storageService.uploadFile(file)
	}
}
