import { SessionStore } from '@backend/auth'
import { ForbiddenException, Injectable } from '@nestjs/common'
import { randomUUID } from 'node:crypto'
import { AWS_OPTIONS, STORAGE_OPTIONS } from '../../../config'
import { FileUploadResponse } from '../types'
import { MulterFile } from 'nestjs-busboy'
import { EventEmitter2 } from '@nestjs/event-emitter'
import { FileUploadEventOptions } from '../consumers'

@Injectable()
export class StorageService {
	constructor(private readonly _eventEmitter: EventEmitter2) {}

	async uploadFile(file: MulterFile): Promise<FileUploadResponse> {
		const tenantId = SessionStore.tenantId
		if (!tenantId) throw new ForbiddenException()

		const fileKey = randomUUID()
		const fileExt = file.originalname.split('.').pop()

		const uniqueFileId = `${fileKey}.${fileExt}`
		const uploadPath = file.mimetype.includes('image')
			? `${tenantId}/${STORAGE_OPTIONS.S3_IMAGES_DIR}/${uniqueFileId}`
			: `${tenantId}/${STORAGE_OPTIONS.S3_GENERIC_DIR}/${uniqueFileId}`

		const bucket = STORAGE_OPTIONS.S3_PUBLIC_BUCKET

		this._eventEmitter.emit('storage.upload', { bucket, file, uploadPath } as FileUploadEventOptions)

		const url = `https://${bucket}.s3.${AWS_OPTIONS.region}.amazonaws.com/${uploadPath}`
		return { url }
	}
}
