import { DatabaseSync } from 'node:sqlite'
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { seedDatabase } from './seed.js'

export type AppDatabase = DatabaseSync

const __dirname = path.dirname(fileURLToPath(import.meta.url))
const dataDir = path.join(__dirname, '../../data')
const dbPath = path.join(dataDir, 'gestion.db')
const schemaPath = path.join(__dirname, 'schema.sql')

if (!fs.existsSync(dataDir)) {
  fs.mkdirSync(dataDir, { recursive: true })
}

const db = new DatabaseSync(dbPath, { enableForeignKeyConstraints: true })
db.exec('PRAGMA journal_mode = WAL')

const schema = fs.readFileSync(schemaPath, 'utf-8')
db.exec(schema)

seedDatabase(db)

export default db
