/**
 * Existing-import duplicate hints (QVS-P2, KAR-971).
 *
 * "nur Hinweis + Wahl (Öffnen/Neu), kein Block" (architecture.md §2) — this
 * never prevents a create; buildQafValueStreamPreview (preview.ts) surfaces
 * the result so a future UI (P3) can offer "open existing" vs "import again"
 * without this service enforcing either choice.
 *
 * `projectId`/`fileHash` MUST be server-derived (qaf-source.ts's QafFileRef),
 * never taken directly from client input — same E4 "erzwungen, nie frei
 * wählbar" discipline the create RPC applies to project_id. The RLS-scoped
 * client also independently prevents any cross-project leak regardless of
 * what is passed in.
 */

import type { SupabaseClient } from '@supabase/supabase-js'
import { logger } from '@/lib/logger'

export interface QvsExistingImport {
  importId: string
  valueStreamId: string
  createdAt: string
  fileHash: string | null
  variantSelector: unknown
}

interface ExistingImportDbRow {
  id: string
  value_stream_id: string
  created_at: string
  file_hash: string | null
  variant_selector: unknown
}

/**
 * Review-Fix 3: `findExistingImports` used to collapse a genuine DB/query
 * error (e.g. `value_stream_imports` missing before the migration is
 * applied) into the same bare `[]` a real "0 duplicates" result produces —
 * despite an in-code comment claiming the opposite ("fails loudly",
 * "fail-closed"). That was wrong: a caller reading `[]` cannot tell "checked,
 * genuinely none" apart from "the check itself failed". This result object
 * makes the distinction explicit so a caller MUST look at `degraded` before
 * treating `items` as a real duplicate count.
 */
export interface FindExistingImportsResult {
  items: QvsExistingImport[]
  /** true when the underlying query failed (relation missing, transient DB
   * error, RLS misconfiguration, …) — `items` is `[]` in this case too, but
   * that `[]` must NEVER be read as "0 duplicates found". Callers must
   * surface "Duplikat-Check nicht verfügbar" to the user instead of
   * reporting a clean result. */
  degraded: boolean
  /** Present only when `degraded` — the raw DB error message, for
   * server-side logging / a future diagnostic surface. Not meant for direct
   * end-user display. */
  degradedReason?: string
}

/** Prior imports of the same source file into the same project, newest
 * first. `items` is empty (never an error thrown) when `fileHash` is null —
 * a file without a hash has nothing reliable to match on, and reporting no
 * hint is safer than matching everything with a null hash; `degraded` is
 * `false` in that case, since nothing was actually attempted or failed.
 *
 * On a genuine DB/query error (e.g. `value_stream_imports` missing before
 * the migration is applied), this degrades to `{ items: [], degraded: true,
 * degradedReason }` — logged server-side (`qvs.duplicates.query_failed`),
 * but NEVER silently collapsed into the same shape a real zero-duplicates
 * result would have (advisory-only service, "nur Hinweis... kein Block",
 * architecture.md §2 — a failed check must never masquerade as a clean one). */
export async function findExistingImports(
  supabase: SupabaseClient,
  params: { projectId: string; fileHash: string | null },
): Promise<FindExistingImportsResult> {
  if (!params.fileHash) return { items: [], degraded: false }

  const { data, error } = await supabase
    .from('value_stream_imports')
    .select('id, value_stream_id, created_at, file_hash, variant_selector')
    .eq('project_id', params.projectId)
    .eq('file_hash', params.fileHash)
    .order('created_at', { ascending: false })

  if (error) {
    logger.warn('qvs.duplicates.query_failed', { message: error.message, code: error.code })
    return { items: [], degraded: true, degradedReason: error.message }
  }
  if (!data) return { items: [], degraded: false }

  return {
    items: (data as ExistingImportDbRow[]).map((r) => ({
      importId: r.id,
      valueStreamId: r.value_stream_id,
      createdAt: r.created_at,
      fileHash: r.file_hash,
      variantSelector: r.variant_selector,
    })),
    degraded: false,
  }
}
