import { Injectable } from '@angular/core';
import { SettingRepository } from '@app/domain/settings/setting.repository';
import { DEFAULT_SETTINGS, ThemeType, UserSettings } from '@app/domain/settings/setting.model';

@Injectable({ providedIn: 'root' })
export class LocalSettingRepository implements SettingRepository {
  private readonly STORAGE_KEY = 'app_user_settings';

  getSettings(): UserSettings {
    const data = localStorage.getItem(this.STORAGE_KEY);
    if (data) {
      return JSON.parse(data);
    }
    return DEFAULT_SETTINGS;
  }

  saveSettings(settings: UserSettings): void {
    localStorage.setItem(this.STORAGE_KEY, JSON.stringify(settings));
  }

  applyTheme(settings: UserSettings): void {
    // Application immédiate de l'effet de bord du thème (Optionnel ici ou dans la Facade)
    if (settings.theme === ThemeType.DARK) {
      document.documentElement.classList.add('dark');
    } else if (settings.theme === ThemeType.SYSTEM) {
      document.documentElement.classList.add(this.getDefaultSystemTheme());
    } else {
      document.documentElement.classList.remove('dark');
    }
  }

  getDefaultSystemTheme(): ThemeType {
    return window.matchMedia('(prefers-color-scheme: dark)').matches
      ? ThemeType.DARK
      : ThemeType.LIGHT;
  }
}
