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

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

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

        }

        const filePath = this.supabase.generatePath(
            `payment/register/attachment`,
            Date.now().toString(),
            file.originalname
        )

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

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