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

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

    async upload(dto: CreateAvatarDto, 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(
            `avatar/image`,
            Date.now().toString(),
            file.originalname
        )

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

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