const assert = require('node:assert/strict')
const fs = require('node:fs')
const os = require('node:os')
const path = require('node:path')
const test = require('node:test')
const { DatabaseSync } = require('node:sqlite')
const JSZip = require('jszip')

const { importBundledSkills } = require('./bundled-skills-import.cjs')

test('bundled skill import publishes complete packages and is idempotent', async () => {
  const root = fs.mkdtempSync(path.join(os.tmpdir(), 'aipros-import-skills-'))
  const bundleRoot = path.join(root, 'bundled-skills')
  const uploadsRoot = path.join(root, 'uploads')
  fs.mkdirSync(path.join(bundleRoot, 'alpha', 'assets'), { recursive: true })
  fs.writeFileSync(path.join(bundleRoot, 'alpha', 'SKILL.md'), '# Alpha\n')
  fs.writeFileSync(path.join(bundleRoot, 'alpha', 'assets', 'prompt.txt'), 'prompt')
  fs.writeFileSync(path.join(bundleRoot, 'manifest.json'), JSON.stringify({
    skillCount: 1,
    skills: [{
      id: 'skill_bundle_alpha',
      name: 'alpha',
      description: 'Alpha skill.',
      sourcePath: 'alpha',
      packageRoot: 'alpha',
      files: 2,
    }],
  }))

  const db = new DatabaseSync(':memory:')
  db.exec(`
    CREATE TABLE categories (id TEXT PRIMARY KEY, path TEXT NOT NULL, status TEXT NOT NULL);
    INSERT INTO categories VALUES ('cat_15_1_2', '15.0 / 15.1 / 15.1.2 流程文件管理', 'active');
    CREATE TABLE skills (
      id TEXT PRIMARY KEY, name TEXT NOT NULL, description TEXT, node_id TEXT NOT NULL, node_path TEXT NOT NULL,
      source TEXT NOT NULL, status TEXT NOT NULL, creator_name TEXT NOT NULL, creator_phone TEXT, creator_email TEXT,
      package_key TEXT, package_size INTEGER, package_name TEXT, visibility TEXT DEFAULT 'public',
      created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL
    );
    CREATE TABLE files (
      id TEXT PRIMARY KEY, r2_key TEXT NOT NULL UNIQUE, filename TEXT NOT NULL, size INTEGER, mime TEXT,
      uploader_phone TEXT, uploader_email TEXT, bound_skill_id TEXT, created_at INTEGER NOT NULL DEFAULT (strftime('%s','now'))
    );
  `)

  try {
    const first = await importBundledSkills({ db, bundleRoot, uploadsRoot, now: new Date('2026-07-20T01:02:03Z') })
    const second = await importBundledSkills({ db, bundleRoot, uploadsRoot, now: new Date('2026-07-20T01:03:03Z') })
    assert.deepEqual(first, { imported: 1, updated: 0, total: 1 })
    assert.deepEqual(second, { imported: 0, updated: 1, total: 1 })

    const skills = db.prepare('SELECT * FROM skills').all()
    assert.equal(skills.length, 1)
    assert.equal(skills[0].status, 'published')
    assert.equal(skills[0].source, 'upload')
    assert.equal(skills[0].visibility, 'public')
    assert.equal(skills[0].created_at, 1784509323)
    assert.equal(skills[0].updated_at, 1784509383)

    const files = db.prepare('SELECT * FROM files').all()
    assert.equal(files.length, 1)
    assert.equal(files[0].bound_skill_id, 'skill_bundle_alpha')
    const packagePath = path.join(uploadsRoot, files[0].r2_key)
    const zip = await JSZip.loadAsync(fs.readFileSync(packagePath))
    assert.deepEqual(Object.keys(zip.files).filter(name => !zip.files[name].dir).sort(), ['SKILL.md', 'assets/prompt.txt'])
  } finally {
    db.close()
    fs.rmSync(root, { recursive: true, force: true })
  }
})
