import { Injectable } from '@nestjs/common';
import { PrismaService } from '../../prisma/prisma.service'

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

  async getNextNumber(runumId: string, reset: string): Promise<number> {
    return this.prisma.$transaction(async (tx) => {
      await tx.txnRunum.upsert({
        where: {
          runumId_reset: {
            runumId,
            reset,
          },
        },
        update: {},
        create: {
          runumId,
          reset,
          nid: 0,
        },
      });

      const updated = await tx.txnRunum.update({
        where: {
          runumId_reset: {
            runumId,
            reset,
          },
        },
        data: {
          nid: {
            increment: 1,
          },
        },
      });

      return updated.nid;
    });
  }

  async findAll() {
    return this.prisma.txnRunum.findMany({
      orderBy: { createdAt: 'desc' },
    });
  }

  async findOne(id: string) {
    return this.prisma.txnRunum.findUnique({
      where: { id },
    });
  }

  async update(id: string, data: any) {
    return this.prisma.txnRunum.update({
      where: { id },
      data,
    });
  }

  async remove(id: string) {
    return this.prisma.txnRunum.delete({
      where: { id },
    });
  }
}