import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { CreateReceiptAliasDto } from './dto/create-receipt-alias.dto';

@Injectable()
export class ReceiptAliasService {
  constructor(private readonly prisma: PrismaService) {}

  findAll() {
    return this.prisma.receiptAlias.findMany({
      include: { product: { select: { id: true, name: true, canonicalName: true } } },
      orderBy: { receiptName: 'asc' },
    });
  }

  async upsert(dto: CreateReceiptAliasDto) {
    const normalized = dto.receiptName.toLowerCase().trim();
    return this.prisma.receiptAlias.upsert({
      where: { receiptName: normalized },
      create: { receiptName: normalized, productId: dto.productId },
      update: { productId: dto.productId },
    });
  }

  remove(id: number) {
    return this.prisma.receiptAlias.delete({ where: { id } });
  }
}
