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

export type SequenceEntityType = 'INVOICE' | 'QUOTE' | 'PROJECT' | 'DEAL' | 'CUSTOMER';

type SequenceSeed = { prefix: string; startNumber: number; padding: number };
type SequenceRow = { nextNumber: number; prefix: string; padding: number };

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

  /** Allocates the next number for a tenant sequence; safe under concurrent requests and usable inside a caller's transaction. */
  async getNextNumber(tenantId: string, entityType: SequenceEntityType, fiscalYear = 'GLOBAL', tx?: Prisma.TransactionClient): Promise<string> {
    if (tx) return this.allocate(tx, tenantId, entityType, fiscalYear);
    return this.prisma.$transaction((inner) => this.allocate(inner, tenantId, entityType, fiscalYear));
  }

  /** Increments the existing sequence row under a single-row lock and returns the number it held before. */
  private async allocate(tx: Prisma.TransactionClient, tenantId: string, entityType: SequenceEntityType, fiscalYear: string): Promise<string> {
    await this.ensureSequence(tenantId, entityType, fiscalYear);
    await tx.$executeRaw`UPDATE number_sequences SET nextNumber = nextNumber + 1, updatedAt = CURRENT_TIMESTAMP(3) WHERE tenantId = ${tenantId} AND entityType = ${entityType} AND fiscalYear = ${fiscalYear}`;
    const [row] = await tx.$queryRaw<SequenceRow[]>`SELECT nextNumber, prefix, padding FROM number_sequences WHERE tenantId = ${tenantId} AND entityType = ${entityType} AND fiscalYear = ${fiscalYear} FOR UPDATE`;
    return `${row.prefix}${String(Number(row.nextNumber) - 1).padStart(Number(row.padding), '0')}`;
  }

  /** Creates the tenant's sequence row on first use with an auto-committed INSERT IGNORE, so parallel first calls never deadlock. */
  private async ensureSequence(tenantId: string, entityType: SequenceEntityType, fiscalYear: string): Promise<void> {
    const exists = await this.prisma.numberSequence.findUnique({ where: { tenantId_entityType_fiscalYear: { tenantId, entityType, fiscalYear } }, select: { id: true } });
    if (exists) return;
    const seed = await this.getDefaultSeed(this.prisma, tenantId, entityType);
    await this.prisma.$executeRaw`INSERT IGNORE INTO number_sequences (id, tenantId, entityType, fiscalYear, prefix, nextNumber, padding, createdAt, updatedAt) VALUES (UUID(), ${tenantId}, ${entityType}, ${fiscalYear}, ${seed.prefix}, ${seed.startNumber}, ${seed.padding}, CURRENT_TIMESTAMP(3), CURRENT_TIMESTAMP(3))`;
  }

  /** Highest numeric suffix among a tenant's existing deal numbers (at least 1040, so the first deal is DEAL-1041). */
  private async highestSuffix(tx: Prisma.TransactionClient | PrismaService, tenantId: string, prefix: string): Promise<number> {
    const rows = await tx.deal.findMany({ where: { tenantId, dealNumber: { startsWith: prefix } }, select: { dealNumber: true } });
    return rows.reduce((max, r) => Math.max(max, Number.parseInt(r.dealNumber.slice(prefix.length), 10) || 0), 1040);
  }

  /** Returns the prefix and starting number used when a tenant's sequence is first created. */
  private async getDefaultSeed(tx: Prisma.TransactionClient | PrismaService, tenantId: string, entityType: SequenceEntityType): Promise<SequenceSeed> {
    const currentYear = new Date().getFullYear();
    switch (entityType) {
      case 'INVOICE':
        return { prefix: `INV-${currentYear}-`, startNumber: (await tx.invoice.count({ where: { tenantId } })) + 1, padding: 4 };
      case 'QUOTE':
        return { prefix: `Q-${currentYear}-`, startNumber: (await tx.quote.count({ where: { tenantId } })) + 1, padding: 4 };
      case 'PROJECT':
        return { prefix: 'PRJ-', startNumber: (await tx.project.count({ where: { tenantId } })) + 1, padding: 4 };
      case 'DEAL':
        return { prefix: 'DEAL-', startNumber: (await this.highestSuffix(tx, tenantId, 'DEAL-')) + 1, padding: 4 };
      case 'CUSTOMER':
        return { prefix: 'CUST-', startNumber: (await tx.customer.count({ where: { tenantId, customerNumber: { not: null } } })) + 1, padding: 4 };
    }
  }
}
