const fs = require('fs/promises')
const path = require('path')
const {
  ensureData,
  closePool,
  listReferencedUploadSources,
} = require('../src/db')

const BACKEND_ROOT = path.join(__dirname, '..')
const TARGET_DIRS = ['avatars', 'custom', 'topics', 'tierlists']

async function main() {
  await ensureData()

  const referenced = new Set(await listReferencedUploadSources())
  const deleted = []
  const missing = []
  let scanned = 0

  for (const dir of TARGET_DIRS) {
    const absoluteDir = path.join(BACKEND_ROOT, 'uploads', dir)
    let entries = []
    try {
      entries = await fs.readdir(absoluteDir, { withFileTypes: true })
    } catch (error) {
      if (error?.code === 'ENOENT') continue
      throw error
    }

    for (const entry of entries) {
      if (!entry.isFile()) continue
      scanned += 1
      const src = `/uploads/${dir}/${entry.name}`
      if (referenced.has(src)) continue
      const absolutePath = path.join(absoluteDir, entry.name)
      try {
        await fs.unlink(absolutePath)
        deleted.push(src)
      } catch (error) {
        if (error?.code === 'ENOENT') missing.push(src)
        else throw error
      }
    }
  }

  console.log(JSON.stringify({ scanned, deletedCount: deleted.length, missingCount: missing.length, deleted, missing }, null, 2))
}

main()
  .catch((error) => {
    console.error(error)
    process.exitCode = 1
  })
  .finally(async () => {
    await closePool()
  })
