/**
 * Zdjęcia stagingu importu: public/uploads/imports/{importId}/
 * Przy imporcie zapisujemy URL-e OLX (szybko); pobieranie lokalne dopiero przy zatwierdzeniu.
 */
import { randomUUID } from 'crypto'
import fs from 'fs/promises'
import path from 'path'
import type { RowDataPacket } from 'mysql2'
import { detectImageFormat, getProjectPublicRoot } from '@/lib/listing-images-upload'
import { getPool } from '@/lib/db'

export const MAX_IMPORT_IMAGE_BYTES = 10 * 1024 * 1024
export const MAX_IMPORT_IMAGES = 20

const USER_AGENT =
  'Mozilla/5.0 (compatible; TwojaLodkaImport/1.0; +https://twojalodka.pl) AppleWebKit/537.36'

export function getImportUploadDir(importId: string): string {
  return path.join(getProjectPublicRoot(), 'uploads', 'imports', importId)
}

export async function saveImportImageUrls(importId: string, imageUrls: string[]): Promise<void> {
  if (!process.env.DATABASE_URL?.trim()) throw new Error('NO_DATABASE')
  const urls = imageUrls.filter((u) => u.startsWith('http')).slice(0, MAX_IMPORT_IMAGES)
  if (urls.length === 0) return

  const pool = getPool()
  let sortOrder = 0
  for (const url of urls) {
    const rowId = randomUUID()
    await pool.execute(
      'INSERT INTO listing_import_images (id, import_id, url_path, source_url, sort_order) VALUES (?, ?, ?, ?, ?)',
      [rowId, importId, url, url, sortOrder],
    )
    sortOrder += 1
  }
}

export async function saveImportImageBuffers(
  importId: string,
  buffers: Buffer[],
): Promise<{ paths: string[] }> {
  if (!process.env.DATABASE_URL?.trim()) throw new Error('NO_DATABASE')
  if (buffers.length === 0) return { paths: [] }
  if (buffers.length > MAX_IMPORT_IMAGES) throw new Error('TOO_MANY_FILES')

  const pool = getPool()
  const dir = getImportUploadDir(importId)
  await fs.mkdir(dir, { recursive: true })

  const paths: string[] = []
  let sortOrder = 0

  for (const buf of buffers) {
    if (buf.length > MAX_IMPORT_IMAGE_BYTES) continue
    const fmt = detectImageFormat(buf)
    if (!fmt) continue

    const ext = fmt === 'jpg' ? 'jpg' : fmt
    const filename = `${randomUUID()}.${ext}`
    const fullPath = path.join(dir, filename)
    const urlPath = `/uploads/imports/${importId}/${filename}`
    const rowId = randomUUID()

    await fs.writeFile(fullPath, buf)
    await pool.execute(
      'INSERT INTO listing_import_images (id, import_id, url_path, sort_order) VALUES (?, ?, ?, ?)',
      [rowId, importId, urlPath, sortOrder],
    )
    paths.push(urlPath)
    sortOrder += 1
  }

  return { paths }
}

/** URL-e do podglądu w panelu admina (OLX CDN lub lokalne ścieżki). */
export async function fetchImportImageDisplayUrls(importId: string): Promise<string[]> {
  if (!process.env.DATABASE_URL?.trim()) return []
  const pool = getPool()
  const [rows] = await pool.execute<RowDataPacket[]>(
    'SELECT url_path, source_url FROM listing_import_images WHERE import_id = ? ORDER BY sort_order ASC',
    [importId],
  )
  return rows.map((r) => {
    const pathVal = String(r.url_path ?? '')
    if (pathVal.startsWith('http')) return pathVal
    const src = String(r.source_url ?? '')
    if (src.startsWith('http')) return src
    return pathVal
  }).filter(Boolean)
}

export async function readImportImageBuffers(importId: string): Promise<Buffer[]> {
  if (!process.env.DATABASE_URL?.trim()) return []
  const pool = getPool()
  const [rows] = await pool.execute<RowDataPacket[]>(
    'SELECT url_path, source_url FROM listing_import_images WHERE import_id = ? ORDER BY sort_order ASC',
    [importId],
  )

  const buffers: Buffer[] = []
  const publicRoot = getProjectPublicRoot()

  for (const row of rows) {
    const urlPath = String(row.url_path ?? '')
    const sourceUrl = String(row.source_url ?? '')
    const remote = [urlPath, sourceUrl].find((u) => u.startsWith('http'))

    if (remote) {
      try {
        const res = await fetch(remote, { headers: { 'User-Agent': USER_AGENT } })
        if (res.ok) {
          const buf = Buffer.from(await res.arrayBuffer())
          if (buf.length > 0) buffers.push(buf)
        }
      } catch {
        /* pomijamy */
      }
      continue
    }

    if (!urlPath.startsWith('/uploads/')) continue
    const rel = urlPath.replace(/^\//, '')
    const abs = path.join(publicRoot, rel)
    try {
      const buf = await fs.readFile(abs)
      buffers.push(buf)
    } catch {
      /* brak pliku */
    }
  }

  return buffers
}
