import Dexie, { Table } from "dexie";
import { GameSession, AppSettings, SavedPlayer } from "../types";

export class BoardScoreDatabase extends Dexie {
  sessions!: Table<GameSession, string>;
  settings!: Table<AppSettings, number>;
  players!: Table<SavedPlayer, string>;

  constructor() {
    super("BoardScoreDatabase");

    this.version(1).stores({
      sessions: "id, gameId, dateStart, status",
      settings: "id",
    });

    // Version 2: Added players table
    this.version(2).stores({
      sessions: "id, gameId, dateStart, status",
      settings: "id",
      players: "id, name, createdAt",
    });
  }
}

export const db = new BoardScoreDatabase();

// Initialize default settings if empty
db.on("populate", async () => {
  await db.settings.add({
    id: 1,
    theme: "system",
    language: "fr",
  });
});
