// duplicates.ts tests (QVS-P2, KAR-971).

import { describe, it, expect, vi } from 'vitest'
import { findExistingImports } from '../duplicates'

vi.mock('@/lib/logger', () => ({ logger: { warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() } }))

function makeSupabase(opts: { data?: unknown[] | null; error?: unknown }) {
  return {
    from: vi.fn(() => ({
      select: vi.fn(() => ({
        eq: vi.fn(() => ({
          eq: vi.fn(() => ({
            order: vi.fn(() => Promise.resolve({ data: opts.data ?? null, error: opts.error ?? null })),
          })),
        })),
      })),
    })),
  }
}

describe('findExistingImports', () => {
  it('returns { items: [], degraded: false } without querying when fileHash is null (nothing reliable to match on)', async () => {
    const supabase = makeSupabase({ data: [] })
    const result = await findExistingImports(supabase as never, { projectId: 'project-1', fileHash: null })
    expect(result).toEqual({ items: [], degraded: false })
    expect(supabase.from).not.toHaveBeenCalled()
  })

  it('maps DB rows to QvsExistingImport, degraded: false', async () => {
    const supabase = makeSupabase({
      data: [
        { id: 'import-1', value_stream_id: 'vsm-1', created_at: '2026-07-01T00:00:00Z', file_hash: 'hash-1', variant_selector: null },
      ],
    })
    const result = await findExistingImports(supabase as never, { projectId: 'project-1', fileHash: 'hash-1' })
    expect(result).toEqual({
      items: [{ importId: 'import-1', valueStreamId: 'vsm-1', createdAt: '2026-07-01T00:00:00Z', fileHash: 'hash-1', variantSelector: null }],
      degraded: false,
    })
  })

  // Review-Fix 3: this used to degrade to a bare [] indistinguishable from a
  // genuine zero-duplicates result (the file header comment even claimed the
  // opposite — "fails loudly"/"fail-closed" — while silently doing neither).
  // Now the query error surfaces as an explicit, checkable `degraded: true`
  // that a caller MUST look at before trusting `items` as a real count.
  it('degrades to { items: [], degraded: true, degradedReason } (never throws) on a query error — e.g. value_stream_imports missing before the migration is applied', async () => {
    const supabase = makeSupabase({ error: { message: 'relation "value_stream_imports" does not exist', code: '42P01' } })
    const result = await findExistingImports(supabase as never, { projectId: 'project-1', fileHash: 'hash-1' })
    expect(result).toEqual({
      items: [],
      degraded: true,
      degradedReason: 'relation "value_stream_imports" does not exist',
    })
  })

  it('returns { items: [], degraded: false } when data is null without an error (defensive)', async () => {
    const supabase = makeSupabase({ data: null })
    const result = await findExistingImports(supabase as never, { projectId: 'project-1', fileHash: 'hash-1' })
    expect(result).toEqual({ items: [], degraded: false })
  })
})
