import Database from "better-sqlite3";
import { join, dirname } from "path";
import { fileURLToPath } from "url";
import { mkdirSync } from "fs";
import bcrypt from "bcryptjs";

const __dirname = dirname(fileURLToPath(import.meta.url));
const DATA_DIR = process.env.DATA_DIR || join(__dirname, "../data");
mkdirSync(DATA_DIR, { recursive: true });

const db = new Database(join(DATA_DIR, "db.sqlite"));

// Enable WAL for better concurrent read performance
db.pragma("journal_mode = WAL");
db.pragma("foreign_keys = ON");

db.exec(`
  CREATE TABLE IF NOT EXISTS students (
    id        TEXT PRIMARY KEY,
    firstName TEXT NOT NULL,
    lastName  TEXT NOT NULL,
    age       INTEGER,
    sex       TEXT,
    weight    REAL,
    height    REAL,
    imc       REAL
  );

  CREATE TABLE IF NOT EXISTS activities (
    id              TEXT PRIMARY KEY,
    studentId       TEXT NOT NULL REFERENCES students(id) ON DELETE CASCADE,
    type            TEXT,
    durationInput   REAL,
    durationUnit    TEXT,
    duration        REAL,
    displayDuration TEXT,
    intensity       TEXT,
    lifestyle       TEXT,
    anxiety         INTEGER DEFAULT 0,
    grade           TEXT,
    date            TEXT,
    createdAt       TEXT DEFAULT (datetime('now'))
  );

  CREATE TABLE IF NOT EXISTS users (
    id           INTEGER PRIMARY KEY AUTOINCREMENT,
    username     TEXT NOT NULL UNIQUE,
    passwordHash TEXT NOT NULL,
    role         TEXT NOT NULL DEFAULT 'admin',
    createdAt    TEXT DEFAULT (datetime('now'))
  );
`);

// Seed default admin (Sanae) if no users exist
const userCount = db.prepare("SELECT COUNT(*) as n FROM users").get().n;
if (userCount === 0) {
  const DEFAULT_PASSWORD = process.env.ADMIN_PASSWORD || "sanae1234";
  const hash = bcrypt.hashSync(DEFAULT_PASSWORD, 10);
  db.prepare(
    "INSERT INTO users (username, passwordHash, role) VALUES (?, ?, ?)",
  ).run("sanae", hash, "admin");
  console.log(
    `[db] Admin user 'sanae' created (password: ${DEFAULT_PASSWORD})`,
  );
}

export default db;
