import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';

/// A single authenticated user.
class AuthUser {
  final String email;
  final String name;
  final String role;
  final String token;

  const AuthUser({
    required this.email,
    required this.name,
    required this.role,
    required this.token,
  });
  
  Map<String, dynamic> toJson() => {
    'email': email,
    'name': name,
    'role': role,
    'token': token,
  };
  
  factory AuthUser.fromJson(Map<String, dynamic> json) => AuthUser(
    email: json['email'] as String? ?? '',
    name: json['name'] as String? ?? '',
    role: json['role'] as String? ?? '',
    token: json['token'] as String? ?? '',
  );
}

class AuthService {
  static const String _base = 'https://api.doormile.com/api/v1';

  /// Login with real backend API
  Future<AuthUser?> login(String email, String password) async {
    try {
      final res = await http.post(
        Uri.parse('$_base/admin/login'),
        headers: {'Content-Type': 'application/json'},
        body: jsonEncode({'email': email, 'password': password}),
      ).timeout(const Duration(seconds: 15));
      
      if (res.statusCode == 200) {
        final data = jsonDecode(res.body);
        final token = data['token'] ?? '';
        final userObj = data['user'] ?? {};
        
        // Sometimes APIs return user inside 'data' or directly. Adjusting based on typical JWT responses.
        final emailStr = userObj['email'] ?? email;
        final nameStr = userObj['name'] ?? userObj['first_name'] ?? 'Admin';
        final roleStr = userObj['role'] ?? 'admin';
        
        final user = AuthUser(
          email: emailStr,
          name: nameStr,
          role: roleStr,
          token: token,
        );
        
        final prefs = await SharedPreferences.getInstance();
        await prefs.setString('auth_user_data', jsonEncode(user.toJson()));
        
        return user;
      }
      return null;
    } catch (_) {
      return null;
    }
  }

  /// Restore user from local storage
  Future<AuthUser?> getSavedUser() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final userData = prefs.getString('auth_user_data');
      if (userData != null && userData.isNotEmpty) {
        return AuthUser.fromJson(jsonDecode(userData));
      }
    } catch (_) {}
    return null;
  }
}
