import 'dart:convert';

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

import '../config/api_config.dart';

/// Ruolo dell'utente autenticato, letto da api_me_role.php.
/// Serve a decidere se mostrare le funzioni insegnante (staff = Admin/teacher).
class UserRole {
  final int roleId;
  final String roleName;
  final bool isStaff;

  const UserRole({
    required this.roleId,
    required this.roleName,
    required this.isStaff,
  });

  factory UserRole.fromMap(Map<String, dynamic> m) => UserRole(
    roleId: (m['role_id'] as num?)?.toInt() ?? 0,
    roleName: (m['role_name'] ?? '').toString(),
    isStaff: m['is_staff'] == true,
  );

  /// Fallback sicuro: utente normale, nessun accesso staff.
  static const UserRole guest = UserRole(
    roleId: 0,
    roleName: '',
    isStaff: false,
  );
}

class RoleService {
  static Uri _u(String path, [Map<String, String>? q]) => Uri.parse(
    '${ApiConfig.laravelApiBase}/$path',
  ).replace(queryParameters: q);

  static Future<UserRole> fetchMyRole({required String token}) async {
    final res = await http.get(
      _u('api_me_role.php'),
      headers: {'Accept': 'application/json', 'Authorization': 'Bearer $token'},
    );

    if (res.statusCode != 200) {
      throw Exception('Role failed (${res.statusCode}): ${res.body}');
    }

    final data = jsonDecode(res.body) as Map<String, dynamic>;
    if (data['success'] != true) {
      throw Exception(data['message'] ?? 'Role error');
    }

    return UserRole.fromMap(data);
  }
}
