import { inject, Injectable, signal } from '@angular/core';
import { ThemeType, UserSettings } from '@app/domain/settings/setting.model';
import { GetSettingsUseCase } from '../../application/settings/get-settings.usecase';
import { UpdateSettingsUseCase } from '../../application/settings/update-settings.usecase';
import { SETTING_REPOSITORY_TOKEN } from '@app/infrastructure/settings/setting-repository.token';
import { ApplyThemeUsecase } from '../../application/settings/apply-theme.usecase';
import { GetDefaultSystemThemeUsecase } from '../../application/settings/get-default-system-theme.usecase';

@Injectable({ providedIn: 'root' })
export class SettingsFacade {
  private readonly settingRepository = inject(SETTING_REPOSITORY_TOKEN);

  private readonly getSettingsUseCase = new GetSettingsUseCase(this.settingRepository);
  private readonly updateSettingsUseCase = new UpdateSettingsUseCase(this.settingRepository);
  private readonly applyThemeUseCase = new ApplyThemeUsecase(this.settingRepository);
  private readonly getDefaultSystemThemeUseCase = new GetDefaultSystemThemeUsecase(
    this.settingRepository
  );

  readonly settings = signal<UserSettings>(this.getSettingsUseCase.execute());

  constructor() {
    const initialSettings = {
      ...this.settings(),
      theme: this.themeMode(),
    };
    this.applyThemeSettings(initialSettings);
  }

  applyThemeSettings(initialSettings: UserSettings) {
    this.applyThemeUseCase.execute(initialSettings);
  }

  loadSettings(): void {
    this.getSettingsUseCase.execute();
  }

  updateSettings(settings: UserSettings): void {
    const settingReceived = {
      ...this.settings(),
      theme: settings.theme,
      privacy: {
        isProfilePublic: settings.privacy.isProfilePublic,
        showEmail: settings.privacy.showEmail,
        showPhone: settings.privacy.showPhone,
        allowGeolocation: settings.privacy.allowGeolocation,
      },
    };
    this.updateSettingsUseCase.execute(settingReceived);
    this.applyThemeSettings(settingReceived);
  }

  private themeMode(): ThemeType {
    let theme = '';

    switch (this.settings().theme) {
      case 'light':
        theme = 'light';
        break;
      case 'dark':
        theme = 'dark';
        break;
      case 'system':
        theme = this.getDefaultSystemThemeUseCase.execute() ? 'dark' : 'light';
        break;
    }
    return theme as ThemeType;
  }
}
