/**
 * src/db.js
 * 使用 Node.js 24 内置 node:sqlite（无需安装额外依赖）
 * 提供 D1-compatible 异步 API，让所有路由代码 c.env.DB → DB 零改动
 */
import { DatabaseSync } from 'node:sqlite'
import { fileURLToPath } from 'url'
import path from 'path'
import fs from 'fs'

const __dirname = path.dirname(fileURLToPath(import.meta.url))
const DB_PATH = process.env.DB_PATH || path.join(__dirname, '../data/aipro.db')
fs.mkdirSync(path.dirname(DB_PATH), { recursive: true })

const sqlite = new DatabaseSync(DB_PATH)
// PRAGMA 通过 exec 执行（node:sqlite 没有 pragma() 方法）
sqlite.exec('PRAGMA journal_mode = WAL')
sqlite.exec('PRAGMA busy_timeout = 5000')
sqlite.exec('PRAGMA foreign_keys = ON')

// D1-compatible async shim
class D1Stmt {
  constructor(db, sql, args) {
    this._db = db
    this._sql = sql
    this._args = args || []
  }
  bind(...args) {
    return new D1Stmt(this._db, this._sql, args)
  }
  async all() {
    return { results: this._db.prepare(this._sql).all(...this._args) }
  }
  async first() {
    return this._db.prepare(this._sql).get(...this._args) ?? null
  }
  async run() {
    return this._db.prepare(this._sql).run(...this._args)
  }
}

export const DB = {
  prepare(sql) {
    return new D1Stmt(sqlite, sql)
  }
}

export { sqlite as rawDB }
