import 'package:uuid/uuid.dart';
import '../../models/user_model.dart';
import '../interfaces/user_service.dart';
import '../api/api_client.dart';
import 'mock_data.dart';

class MockUserService implements UserService {
  final List<UserModel> _users = List.from(MockData.users);
  final _uuid = const Uuid();

  @override
  Future<List<UserModel>> getUsers() async {
    await Future.delayed(const Duration(milliseconds: 400));
    return List.unmodifiable(_users);
  }

  @override
  Future<CreateUserResult> createUser(
    String username, {
    String? phoneNumber,
  }) async {
    await Future.delayed(const Duration(milliseconds: 500));

    if (_users.any((u) => u.username == username)) {
      throw const ApiException(
          statusCode: 400, message: 'این نام کاربری قبلاً ثبت شده است');
    }

    final secret = _generateSecret();
    final user = UserModel(
      id: 'u-${_uuid.v4().substring(0, 8)}',
      username: username,
      phoneNumber: phoneNumber,
      role: UserRole.member,
      isActive: true,
      createdAt: DateTime.now(),
    );
    _users.add(user);
    return (user: user, secret: secret);
  }

  @override
  Future<String> resetSecret(String userId) async {
    await Future.delayed(const Duration(milliseconds: 400));

    final idx = _users.indexWhere((u) => u.id == userId);
    if (idx == -1) {
      throw const ApiException(statusCode: 404, message: 'کاربر یافت نشد');
    }
    return _generateSecret();
  }

  @override
  Future<void> logoutUser(String userId) async {
    await Future.delayed(const Duration(milliseconds: 300));
    final idx = _users.indexWhere((u) => u.id == userId);
    if (idx == -1) {
      throw const ApiException(statusCode: 404, message: 'کاربر یافت نشد');
    }
  }

  String _generateSecret() {
    final uuid = _uuid.v4().replaceAll('-', '');
    return uuid.substring(0, 16);
  }
}
