using cfs_tracker.Models; using cfs_tracker.Services; using SQLite; namespace cfs_tracker.Data; public sealed class AppDatabase { private readonly DatabaseLocationService _databaseLocationService; private readonly SemaphoreSlim _initLock = new(1, 1); private SQLiteAsyncConnection? _connection; private bool _initialized; public AppDatabase(DatabaseLocationService databaseLocationService) { _databaseLocationService = databaseLocationService; } public async Task InitAsync() { if (_initialized) return; await _initLock.WaitAsync(); try { if (_initialized) return; var dbPath = _databaseLocationService.ResolveDatabasePath(); var directory = Path.GetDirectoryName(dbPath); if (!string.IsNullOrWhiteSpace(directory)) Directory.CreateDirectory(directory); _connection = new SQLiteAsyncConnection(dbPath); await _connection.ExecuteAsync("PRAGMA foreign_keys = ON;"); await _connection.CreateTableAsync(); await _connection.CreateTableAsync(); await _connection.CreateTableAsync(); await _connection.CreateTableAsync(); await _connection.CreateTableAsync(); await _connection.CreateTableAsync(); await _connection.ExecuteAsync(@" CREATE TABLE IF NOT EXISTS HealthEntrySymptom ( Id INTEGER PRIMARY KEY AUTOINCREMENT, HealthEntryId INTEGER NOT NULL, SymptomItemId INTEGER NOT NULL );"); await _connection.ExecuteAsync( "CREATE INDEX IF NOT EXISTS IX_HealthEntrySymptom_HealthEntryId ON HealthEntrySymptom(HealthEntryId);"); await _connection.ExecuteAsync( "CREATE INDEX IF NOT EXISTS IX_HealthEntrySymptom_SymptomItemId ON HealthEntrySymptom(SymptomItemId);"); _initialized = true; } finally { _initLock.Release(); } } public string CurrentPath => _databaseLocationService.ResolveDatabasePath(); public SQLiteAsyncConnection Connection => _connection ?? throw new InvalidOperationException("Database has not been initialized yet."); }