import 'package:flutter/foundation.dart';

import '../models/user_settings.dart';
import '../models/school_settings.dart';
import '../services/settings_api.dart';

class AppSettingsStore extends ChangeNotifier {
  bool loading = false;
  String error = '';

  int? schoolId;

  UserSettings? userSettings;
  SchoolSettings? schoolSettings;

  bool get isReady => userSettings != null && schoolSettings != null;

  Future<void> loadForSchool({
    required String token,
    required int schoolId,
  }) async {
    loading = true;
    error = '';
    notifyListeners();

    try {
      // puoi farle in parallelo
      final results = await Future.wait([
        SettingsApi.fetchUserSettings(token: token),
        SettingsApi.fetchSchoolSettings(token: token, schoolId: schoolId),
      ]);

      userSettings = results[0] as UserSettings;
      schoolSettings = results[1] as SchoolSettings;
      this.schoolId = schoolId;
    } catch (e) {
      error = e.toString();
      // se fallisce, meglio lasciare null per evitare dati “mezzi vecchi”
      userSettings = null;
      schoolSettings = null;
      this.schoolId = null;
    } finally {
      loading = false;
      notifyListeners();
    }
  }

  void clear() {
    loading = false;
    error = '';
    schoolId = null;
    userSettings = null;
    schoolSettings = null;
    notifyListeners();
  }
}
