import { createHash } from 'node:crypto'
import { existsSync } from 'node:fs'
import { readFile } from 'node:fs/promises'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { saveBufferToFileStorage } from '../src/lite/file-storage.mjs'
import { executeSql, sqlLiteral } from '../src/lite/pg.mjs'

const brandLogoFileId = 'd1b1d1b1-2026-4000-9000-000000000001'
const moduleDir = path.dirname(fileURLToPath(import.meta.url))
const backendRoot = path.resolve(moduleDir, '..')
const repoRoot = path.resolve(backendRoot, '..')
const sourceCandidates = [
  process.env.BRAND_LOGO_SOURCE_FILE || '',
  path.join(backendRoot, 'assets/dlbdi-logo.jpg'),
  path.join(repoRoot, 'web/public/assets/dlbdi-logo.jpg'),
].filter(Boolean)

const sourceFile = sourceCandidates.find((candidate) => existsSync(candidate))
if (!sourceFile) {
  throw new Error(`Brand logo source file not found. Checked: ${sourceCandidates.join(', ')}`)
}

const body = await readFile(sourceFile)
const stored = await saveBufferToFileStorage(body, 'dlbdi-logo.jpg', 'image/jpeg')
if (process.env.NODE_ENV === 'production' && stored.storageDriver !== 's3') {
  throw new Error('Brand logo must be stored in S3/object storage in production.')
}

const checksum = createHash('sha256').update(body).digest('hex')

await executeSql(`
  insert into uploaded_files (
    id, file_name, mime_type, file_size, content_base64,
    storage_driver, bucket, object_key, storage_path, checksum,
    visibility, owner_type, owner_id
  )
  values (
    ${sqlLiteral(brandLogoFileId)}::uuid,
    'dlbdi-logo.jpg',
    'image/jpeg',
    ${body.length},
    '',
    ${sqlLiteral(stored.storageDriver || 's3')},
    ${sqlLiteral(stored.bucket || '')},
    ${sqlLiteral(stored.objectKey || '')},
    ${sqlLiteral(stored.storagePath || '')},
    ${sqlLiteral(checksum)},
    'public',
    'site_asset',
    'brand_logo'
  )
  on conflict (id) do update set
    file_name = excluded.file_name,
    mime_type = excluded.mime_type,
    file_size = excluded.file_size,
    content_base64 = '',
    storage_driver = excluded.storage_driver,
    bucket = excluded.bucket,
    object_key = excluded.object_key,
    storage_path = excluded.storage_path,
    checksum = excluded.checksum,
    visibility = excluded.visibility,
    owner_type = excluded.owner_type,
    owner_id = excluded.owner_id;
`)

console.log(JSON.stringify({
  id: brandLogoFileId,
  storageDriver: stored.storageDriver,
  bucket: stored.bucket || '',
  objectKey: stored.objectKey || '',
  fileSize: body.length,
  source: path.relative(repoRoot, sourceFile),
}))
