import { createHash } from 'node:crypto'
import { beforeEach, describe, expect, it, vi } from 'vitest'

const state = vi.hoisted(() => ({ found: null as null | { id: string; file_name: string }, filters: [] as Array<[string, unknown]> }))
vi.mock('server-only', () => ({}))
vi.mock('@/lib/supabase/admin', () => ({
  createAdminClient: () => ({
    from: () => {
      const q = {
        select: () => q,
        eq: (k: string, v: unknown) => { state.filters.push([k, v]); return q },
        limit: () => q,
        maybeSingle: async () => ({ data: state.found, error: null }),
      }
      return q
    },
  }),
}))
import { DUPLICATE_PERMIT_MESSAGE, fileSha256, findTripPermitByHash, uniqueByContent } from '@/lib/data/document-fingerprint'

const file = (text: string, name = 'permit.pdf') => new File([text], name, { type: 'application/pdf' })

beforeEach(() => { state.found = null; state.filters = [] })

describe('exact-duplicate permit files', () => {
  it('fingerprints the exact bytes as lowercase SHA-256 hex (the Brain\'s file_sha256)', async () => {
    expect(await fileSha256(file('abc'))).toBe(createHash('sha256').update('abc').digest('hex'))
  })
  it('keeps one copy of each identical file in an upload, in order, whatever the names', async () => {
    const { unique, skipped } = await uniqueByContent([file('A', 'a.pdf'), file('B', 'b.pdf'), file('A', 'copy-of-a.pdf')])
    expect(unique.map((u) => u.file.name)).toEqual(['a.pdf', 'b.pdf'])
    expect(skipped).toBe(1)
  })
  it('looks only at permit documents on the same trip (other trips are allowed, N9)', async () => {
    state.found = { id: 'doc-1', file_name: 'permit.pdf' }
    expect(await findTripPermitByHash('trip-1', 'h')).toEqual({ id: 'doc-1', file_name: 'permit.pdf' })
    expect(state.filters).toEqual([['trip_id', 'trip-1'], ['kind', 'permit'], ['content_hash', 'h']])
  })
  it('tells the uploader in plain words', () => {
    expect(DUPLICATE_PERMIT_MESSAGE).toBe('This exact file is already on this trip.')
  })
})
