import assert from 'node:assert/strict'
import test from 'node:test'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { fileURLToPath } from 'node:url'

const __dirname = path.dirname(fileURLToPath(import.meta.url))
const workerRoot = path.resolve(__dirname, '../..')

test('created skill packages are saved where the download route can read them', async (t) => {
  const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'aipros-skill-upload-'))
  process.env.DB_PATH = path.join(tempRoot, 'test.db')
  delete process.env.UPLOADS_DIR

  const { default: app } = await import('../index.js')
  const { rawDB } = await import('../db.js')

  const initSql = fs.readFileSync(path.join(workerRoot, 'migrations/0001_init.sql'), 'utf8')
  const visibilitySql = fs.readFileSync(path.join(workerRoot, 'migrations/0007_skill_visibility.sql'), 'utf8')
  rawDB.exec(initSql)
  rawDB.exec(visibilitySql)
  rawDB.prepare(
    `INSERT INTO categories (id, parent_id, code, name, level, path, status, sort)
     VALUES (?, NULL, ?, ?, 1, ?, 'active', 1)`
  ).run('cat_upload_path', '1.0', '测试节点', '测试节点')

  let packageKey = ''
  t.after(() => {
    if (packageKey) {
      for (const root of [path.join(workerRoot, 'uploads'), path.join(workerRoot, 'src/uploads')]) {
        fs.rmSync(path.join(root, packageKey), { force: true })
      }
    }
    fs.rmSync(tempRoot, { recursive: true, force: true })
  })

  const createRes = await app.request('/api/skills', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-User-Email': 'creator@example.com',
    },
    body: JSON.stringify({
      name: '自动打包测试',
      description: '# 自动打包测试\n\n这是上传链路检查。',
      node_id: 'cat_upload_path',
      source: 'create',
      creator_name: '创建者',
    }),
  })

  assert.equal(createRes.status, 201)

  const skillId = (await createRes.json()).data.id
  const row = rawDB.prepare('SELECT package_key FROM skills WHERE id = ?').get(skillId)
  packageKey = row.package_key
  assert.match(packageKey, /^pkg\/\d{4}-\d{2}-\d{2}\//)

  const downloadRes = await app.request(`/api/uploads/download?key=${encodeURIComponent(packageKey)}`)

  assert.equal(downloadRes.status, 200)
  assert.equal(downloadRes.headers.get('Content-Type'), 'application/octet-stream')
})
