import { Prisma } from '@prisma/client';

import { AppError, AppErrorCode } from '../../errors/app-error';

const retentionMessage = 'Signed document evidence is retained and cannot be deleted or reassigned.';
const postgresRetentionError = /PostgresError\s*\{\s*code:\s*"23514",\s*message:\s*"SIGNING_EVIDENCE_RETAINED:/;

export const rethrowSigningEvidenceError = (error: unknown): never => {
  // Normalize only the installed retention trigger, after PostgreSQL has rolled back
  // the failing statement/transaction. Other constraints and failures retain their identity.
  const retainedUnknownError =
    error instanceof Prisma.PrismaClientUnknownRequestError && postgresRetentionError.test(error.message);
  const retainedRawError =
    error instanceof Prisma.PrismaClientKnownRequestError &&
    error.code === 'P2010' &&
    error.meta?.code === '23514' &&
    typeof error.meta.message === 'string' &&
    error.meta.message.startsWith('SIGNING_EVIDENCE_RETAINED:');

  if (retainedUnknownError || retainedRawError) {
    throw new AppError(AppErrorCode.INVALID_REQUEST, { message: retentionMessage });
  }

  throw error;
};
