/**
 * Ledger Image Service - Account photos
 */
import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';

const KIND_LEDGER = 1;

@Injectable()
export class LedgerImageService {
  constructor(private prisma: PrismaService) {}

  async findByActNo(actNo: string) {
    const row = await this.prisma.ledgerImage.findUnique({
      where: { kind_tno: { kind: KIND_LEDGER, tno: actNo } },
    });
    if (!row) return null;
    return {
      ...row,
      img: row.img ? row.img.toString('base64') : null,
    };
  }

  async upsert(actNo: string, imgBase64: string | null, note?: string) {
    const img = imgBase64 ? Buffer.from(imgBase64, 'base64') : null;
    const row = await this.prisma.ledgerImage.upsert({
      where: { kind_tno: { kind: KIND_LEDGER, tno: actNo } },
      create: { kind: KIND_LEDGER, tno: actNo, img, note: note ?? null },
      update: { img, note: note ?? null },
    });
    return { ...row, img: row.img ? row.img.toString('base64') : null };
  }

  async delete(actNo: string) {
    try {
      return await this.prisma.ledgerImage.delete({
        where: { kind_tno: { kind: KIND_LEDGER, tno: actNo } },
      });
    } catch {
      throw new NotFoundException(`No image for account ${actNo}`);
    }
  }
}
