import 'dart:convert';
import 'package:injectable/injectable.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:krow/core/data/models/staff/staff.dart';
import 'package:krow/core/data/models/staff_role.dart';
import 'package:firebase_auth/firebase_auth.dart';

@LazySingleton()
class ProfileLocalProvider {
  Future<String> _getUserId() async {
    final user = FirebaseAuth.instance.currentUser;
    if (user != null) {
      return user.uid;
    } else {

      throw Exception('No user logged in');
    }
  }

  Future<void> saveStaff(Staff staff) async {
    final prefs = await SharedPreferences.getInstance();
    final userId = await _getUserId();
    final staffJson = jsonEncode(staff.toJson());
    await prefs.setString('cached_staff_$userId', staffJson);
  }

  Future<Staff?> loadStaff() async {
    final prefs = await SharedPreferences.getInstance();
    final userId = await _getUserId();
    final staffJson = prefs.getString('cached_staff_$userId');
    if (staffJson != null) {
      return Staff.fromJson(jsonDecode(staffJson));
    }
    return null;
  }

  Future<void> saveRoles(List<StaffRole> roles) async {
    final prefs = await SharedPreferences.getInstance();
    final userId = await _getUserId();
    final rolesJson = jsonEncode(roles.map((role) => role.toJson()).toList());
    await prefs.setString('cached_roles_$userId', rolesJson);
  }

  Future<List<StaffRole>?> loadRoles() async {
    final prefs = await SharedPreferences.getInstance();
    final userId = await _getUserId();
    final rolesJson = prefs.getString('cached_roles_$userId');
    if (rolesJson != null) {
      final List<dynamic> rolesList = jsonDecode(rolesJson);
      return rolesList.map((json) => StaffRole.fromJson(json)).toList();
    }
    return null;
  }
}