import { db } from './database.js'
import { settingsRepository } from './repositories/settingsRepository.js'
import { i18next } from '../i18n'

// Full startup sequence: DB init plus persisted settings applied before the
// first render. Re-callable: database.init() resets itself on failure, so
// calling this again (App.vue's Retry button) restarts from scratch once the
// network is back.
export async function bootstrapDatabase() {
  try {
    const info = await db.init()
    console.log('Database initialized:', info)

    // Apply persisted settings before first render
    const lang = await settingsRepository.get('language')
    if (lang) {
      i18next.changeLanguage(lang)
    }
    const theme = await settingsRepository.get('theme')
    if (theme) {
      document.documentElement.setAttribute('data-theme', theme)
    }

    document.documentElement.removeAttribute('data-db-error')

    if (db.migrationPending) {
      // App stays paused: App.vue shows the blocking migration screen
      document.documentElement.setAttribute('data-db-migration', 'pending')
      return { migrationPending: db.migrationPending }
    }

    document.documentElement.setAttribute('data-db-ready', 'true')
    return {}
  } catch (err) {
    console.error('Database initialization failed:', err)
    document.documentElement.setAttribute('data-db-error', err.message)
    throw err
  }
}
