import { BadRequestException, Injectable, Logger } from '@nestjs/common';
import { PrismaService } from 'src/prisma/prisma.service';
import { SupabaseService } from 'src/supabase/supabase.service';
import { CreateEventUploadDto } from './dto/create-event-upload';

@Injectable()
export class EventUplaodService {
    private readonly logger = new Logger(EventUplaodService.name)
    constructor(
        private readonly prisma: PrismaService,
        private readonly supabase: SupabaseService
    ) { }

    async upload(dto: CreateEventUploadDto, file: Express.Multer.File) {
        if (!file) {
            this.logger.error("Must have event image to upload")
            throw new BadRequestException("Must have event image to upload")

        }

        const filePath = this.supabase.generatePath(
            `event/image`,
            Date.now().toString(),
            file.originalname
        )

        const fileUrl = await this.supabase.upload(
            'kpdh',
            filePath,
            file.buffer,
            file.mimetype
        )

        return await this.prisma.eventImage.create({
            data: {
                imageUrl: fileUrl,
                fileName: file.originalname,
                fileType: file.mimetype,
                uploadedBy: dto.userId,
                createdBy: dto.userId,
                uploadedAt: new Date()
            }
        })
    }
}
