using cfs_tracker.Helpers; using cfs_tracker.Models; namespace cfs_tracker.Data; public class AppearanceRepository { private readonly AppDatabase _database; public AppearanceRepository(AppDatabase database) { _database = database; } public async Task EnsureDefaultsAsync() { await _database.InitAsync(); foreach (var pair in AppearanceDefaults.All) await InsertIfMissingAsync(pair.Key, pair.Value); } public async Task ResetAsync() { await _database.InitAsync(); await _database.Connection.DeleteAllAsync(); await EnsureDefaultsAsync(); } public async Task ResetToDefaultsAsync() { await ResetAsync(); } public async Task> GetAllAsync() { await _database.InitAsync(); return await _database.Connection.Table() .OrderBy(x => x.Key) .ToListAsync(); } public async Task> GetMapAsync() { var items = await GetAllAsync(); return items.ToDictionary(x => x.Key, x => x.Value); } public async Task SaveAsync(string key, string value) { await _database.InitAsync(); var cleanKey = NormalizeKey(key); var cleanValue = NormalizeValue(value); var existing = await _database.Connection.Table() .FirstOrDefaultAsync(x => x.Key == cleanKey); if (existing is null) { await _database.Connection.InsertAsync(new AppearanceSetting { Key = cleanKey, Value = cleanValue }); return; } existing.Value = cleanValue; await _database.Connection.UpdateAsync(existing); } public async Task UpsertAsync(string key, string value) { await SaveAsync(key, value); } private async Task InsertIfMissingAsync(string key, string value) { var cleanKey = NormalizeKey(key); var cleanValue = NormalizeValue(value); var existing = await _database.Connection.Table() .FirstOrDefaultAsync(x => x.Key == cleanKey); if (existing is not null) return; await _database.Connection.InsertAsync(new AppearanceSetting { Key = cleanKey, Value = cleanValue }); } private static string NormalizeKey(string key) { var cleanKey = (key ?? string.Empty).Trim(); if (string.IsNullOrWhiteSpace(cleanKey)) throw new ArgumentException("Appearance key must not be empty.", nameof(key)); return cleanKey; } private static string NormalizeValue(string value) { return (value ?? string.Empty).Trim(); } }