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

export class JobCancellationWonError extends Error {
  constructor() {
    super('Translation job is no longer processing.');
    this.name = 'JobCancellationWonError';
  }
}

export async function lockProcessingJob(
  tx: { $queryRaw: PrismaClient['$queryRaw'] },
  jobId: string,
  leaseId: string
): Promise<void> {
  const rows = await tx.$queryRaw<Array<{ id: string }>>`
    SELECT id
    FROM "translation_jobs"
    WHERE id = ${jobId}::uuid AND status = 'processing' AND processing_lease_id = ${leaseId}::uuid
    FOR UPDATE
  `;
  if (!Array.isArray(rows) || rows.length !== 1) {
    throw new JobCancellationWonError();
  }
}
