import Database from "better-sqlite3";
import fs from "fs";
import path from "path";

const COLORING_MANIFEST_PATH = path.resolve(
  __dirname,
  "../../../../templates/coloring/manifest.json"
);

export function seedTemplates(db: Database.Database): void {
  // 检查 coloring 模板是否已注册
  const existing = db
    .prepare("SELECT id FROM templates WHERE id = ?")
    .get("coloring");

  if (existing) {
    // 更新 manifest（开发阶段可能频繁变更）
    const manifest = fs.readFileSync(COLORING_MANIFEST_PATH, "utf-8");
    const manifestJson = JSON.parse(manifest);
    db.prepare(
      "UPDATE templates SET manifest = ?, name = ?, updated_at = datetime('now') WHERE id = ?"
    ).run(manifest, manifestJson.name, "coloring");
    console.log("[db] Template 'coloring' updated");
    return;
  }

  // 首次注册
  const manifest = fs.readFileSync(COLORING_MANIFEST_PATH, "utf-8");
  const manifestJson = JSON.parse(manifest);
  db.prepare(
    "INSERT INTO templates (id, name, manifest) VALUES (?, ?, ?)"
  ).run("coloring", manifestJson.name, manifest);
  console.log("[db] Template 'coloring' seeded");
}
