import { createDbService } from '@/server/services/db.js';
/**
 * TM eviction module — Plan 4 Task 2.
 *
 * Marks a deal_translation field as STALE (clears sourceHash) and re-enqueues
 * the deal for translation with forceFresh=true so the worker bypasses TM
 * and calls Gemini fresh.
 */

import { env } from '@/server/env.js';
import { enqueueDealTranslation } from '@/server/translation/jobs/enqueue.js';
import { evictDealTranslationField } from '@/server/db/queries/translation/deal-translations.js';

export type TranslatableField = 'title' | 'description' | 'specialInstructions';
type SourceHashField =
  | 'titleSourceHash'
  | 'descriptionSourceHash'
  | 'specialInstructionsSourceHash';

const FIELD_HASH_MAP = {
  title: 'titleSourceHash',
  description: 'descriptionSourceHash',
  specialInstructions: 'specialInstructionsSourceHash',
} satisfies Record<TranslatableField, SourceHashField>;

/**
 * Reset the field-level sourceHash so the worker re-runs translation for
 * this field on next run, and sets the translation row status to STALE.
 */
export async function evictTmEntries(opts: {
  dealId: string;
  locale: string;
  field: TranslatableField;
}): Promise<void> {
  const db = createDbService({ DATABASE_URL: env.DATABASE_URL });
  const hashField = FIELD_HASH_MAP[opts.field];

  await evictDealTranslationField(db, { dealId: opts.dealId, locale: opts.locale, hashField });
}

/**
 * Mark a translation field as bad and re-trigger translation.
 * Called from the report endpoint (Task 14).
 *
 * forceFresh=true tells the worker to skip TM lookup — without this,
 * the worker would TM-hit the same bad entries and reporter sees no change.
 */
export async function markBadAndRetranslate(input: {
  dealId: string;
  locale: string;
  field: TranslatableField;
  reporterId: string;
}): Promise<void> {
  await evictTmEntries(input);

  const db = createDbService({ DATABASE_URL: env.DATABASE_URL });
  await enqueueDealTranslation(db, input.dealId, {
    targetLocales: [input.locale],
    forceFresh: true,
  });
}
