import 'server-only'

import { createHash } from 'node:crypto'
import { createAdminClient } from '@/lib/supabase/admin'

/**
 * Exact-duplicate permit files (Nash, owner answer 006; N9 for other trips):
 * the same permit file can't be uploaded twice to the same trip — one copy is
 * kept and the uploader is told. The same file on a different trip is allowed.
 * The fingerprint is the SHA-256 of the exact bytes, stored in the existing
 * documents.content_hash column (migration 0017), lowercase hex — the same
 * value the Brain returns as file_sha256.
 */
export const DUPLICATE_PERMIT_MESSAGE = 'This exact file is already on this trip.'

export async function fileSha256(file: Blob): Promise<string> {
  return createHash('sha256').update(Buffer.from(await file.arrayBuffer())).digest('hex')
}

/** One copy of each identical file, in upload order, with its fingerprint. */
export async function uniqueByContent<T extends Blob>(files: T[]): Promise<{ unique: Array<{ file: T; hash: string }>; skipped: number }> {
  const seen = new Set<string>()
  const unique: Array<{ file: T; hash: string }> = []
  for (const file of files) {
    const hash = await fileSha256(file)
    if (seen.has(hash)) continue
    seen.add(hash)
    unique.push({ file, hash })
  }
  return { unique, skipped: files.length - unique.length }
}

/** An existing permit document on this trip with the same fingerprint, if any. */
export async function findTripPermitByHash(tripId: string, hash: string): Promise<{ id: string; file_name: string | null } | null> {
  const { data } = await createAdminClient().from('documents').select('id, file_name')
    .eq('trip_id', tripId).eq('kind', 'permit').eq('content_hash', hash).limit(1).maybeSingle()
  return (data as { id: string; file_name: string | null } | null) ?? null
}
