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

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

function execMigration(rawDB, file) {
  rawDB.exec(fs.readFileSync(path.join(workerRoot, 'migrations', file), 'utf8'))
}

test('API keys can only be created for published skills', async (t) => {
  const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'aipros-apikey-published-'))
  process.env.DB_PATH = path.join(tempRoot, 'test.db')
  t.after(() => fs.rmSync(tempRoot, { recursive: true, force: true }))

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

  execMigration(rawDB, '0001_init.sql')
  execMigration(rawDB, '0002_skill_stats.sql')
  execMigration(rawDB, '0004_skill_api.sql')
  execMigration(rawDB, '0007_skill_visibility.sql')

  rawDB.prepare(
    `INSERT INTO categories (id, parent_id, code, name, level, path, status, sort)
     VALUES (?, NULL, ?, ?, 1, ?, 'active', 1)`
  ).run('cat_api_key', '1.0', '流程域', '流程域')

  const headers = {
    'Content-Type': 'application/json',
    'X-User-Email': 'owner@example.com',
  }

  const createRes = await app.request('/api/skills', {
    method: 'POST',
    headers,
    body: JSON.stringify({
      name: '调用测试 Skill',
      description: '用于验证 API Key 发布门禁。',
      node_id: 'cat_api_key',
      source: 'create',
      creator_name: 'Owner',
    }),
  })
  assert.equal(createRes.status, 201)
  const skillId = (await createRes.json()).data.id

  const draftKeyRes = await app.request('/api/apikeys', {
    method: 'POST',
    headers,
    body: JSON.stringify({ skill_id: skillId, name: 'draft-key' }),
  })
  assert.equal(draftKeyRes.status, 409)
  const draftKeyBody = await draftKeyRes.json()
  assert.equal(draftKeyBody.error, 'skill_not_published')

  const publishRes = await app.request(`/api/skills/${skillId}`, {
    method: 'PUT',
    headers,
    body: JSON.stringify({ status: 'published', creator_name: 'Owner' }),
  })
  assert.equal(publishRes.status, 200)

  const publishedKeyRes = await app.request('/api/apikeys', {
    method: 'POST',
    headers,
    body: JSON.stringify({ skill_id: skillId, name: 'published-key' }),
  })
  assert.equal(publishedKeyRes.status, 201)
  const keyBody = await publishedKeyRes.json()
  assert.match(keyBody.key, /^sk_live_/)
})
