"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.initDatabase = initDatabase;
const better_sqlite3_1 = __importDefault(require("better-sqlite3"));
const path_1 = __importDefault(require("path"));
const fs_1 = __importDefault(require("fs"));
function initDatabase(storageDir) {
    // 确保 storage 目录存在
    if (!fs_1.default.existsSync(storageDir)) {
        fs_1.default.mkdirSync(storageDir, { recursive: true });
    }
    const dbPath = path_1.default.join(storageDir, "data.db");
    const db = new better_sqlite3_1.default(dbPath);
    // WAL 模式提升并发读取
    db.pragma("journal_mode = WAL");
    db.pragma("foreign_keys = ON");
    // 建表
    db.exec(`
    CREATE TABLE IF NOT EXISTS templates (
      id          TEXT PRIMARY KEY,
      name        TEXT NOT NULL,
      manifest    TEXT NOT NULL,
      created_at  TEXT NOT NULL DEFAULT (datetime('now')),
      updated_at  TEXT NOT NULL DEFAULT (datetime('now'))
    );

    CREATE TABLE IF NOT EXISTS creatives (
      id          TEXT PRIMARY KEY,
      name        TEXT NOT NULL,
      template_id TEXT NOT NULL REFERENCES templates(id),
      theme       TEXT NOT NULL DEFAULT '{}',
      status      TEXT NOT NULL DEFAULT 'draft',
      created_at  TEXT NOT NULL DEFAULT (datetime('now')),
      updated_at  TEXT NOT NULL DEFAULT (datetime('now'))
    );

    CREATE TABLE IF NOT EXISTS creative_assets (
      id          INTEGER PRIMARY KEY AUTOINCREMENT,
      creative_id TEXT NOT NULL REFERENCES creatives(id) ON DELETE CASCADE,
      file_key    TEXT NOT NULL,
      file_name   TEXT NOT NULL,
      file_path   TEXT NOT NULL,
      file_size   INTEGER,
      is_required INTEGER NOT NULL DEFAULT 1,
      created_at  TEXT NOT NULL DEFAULT (datetime('now'))
    );

    CREATE TABLE IF NOT EXISTS builds (
      id            TEXT PRIMARY KEY,
      creative_id   TEXT NOT NULL REFERENCES creatives(id) ON DELETE CASCADE,
      status        TEXT NOT NULL DEFAULT 'pending',
      platforms     TEXT NOT NULL,
      theme_snapshot TEXT NOT NULL,
      results       TEXT,
      error_log     TEXT,
      started_at    TEXT,
      finished_at   TEXT,
      created_at    TEXT NOT NULL DEFAULT (datetime('now'))
    );

    CREATE INDEX IF NOT EXISTS idx_creatives_template ON creatives(template_id);
    CREATE INDEX IF NOT EXISTS idx_builds_creative ON builds(creative_id);
    CREATE INDEX IF NOT EXISTS idx_creative_assets_creative ON creative_assets(creative_id);
  `);
    console.log("[db] Database initialized at", dbPath);
    return db;
}
//# sourceMappingURL=database.js.map