import { Injectable } from "@nestjs/common";
import { Result } from "src/common/errors/result-error.factory";
import { PrismaPostgresService } from "prisma/postgres/prisma-postgres.service";

@Injectable()
export class AttachmentDeleteService {
    constructor(private readonly prisma: PrismaPostgresService) { }

    async deleteAttachment(id: string): Promise<Result<boolean, string>> {
        await this.prisma.client.$transaction(async (tx) => {
            const attachment = await tx.attachments.findUnique({ where: { id: Number(id) } });
            if (!attachment) return { success: false, error: 'ATTACHMENT_NOT_FOUND' };

            // soft-delete
            await tx.attachments.update({ where: { id: Number(id) }, data: { status: 'DELETED' } });

            // decrement refcount
            const dec = await tx.$executeRaw`
                UPDATE "blobs" SET refcount = refcount - 1 
                WHERE sha256 = ${attachment.sha256} AND refcount > 0;`;

            return { ok: true, decremented: dec > 0 };
        });
        return { success: true, data: true };
    }
}