import 'package:bloc/bloc.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'permission_event.dart';
import 'permission_state.dart';
import '../../services/api_client.dart';

class PermissionBloc extends Bloc<PermissionEvent, PermissionState> {
  final ApiClient apiClient;

  PermissionBloc(this.apiClient) : super(PermissionInitial()) {
    on<LoadPermissions>(_onLoadPermissions);
    on<PermissionsReset>(_onPermissionsReset);
  }

  void _onLoadPermissions(
    LoadPermissions event,
    Emitter<PermissionState> emit,
  ) async {
    if (event.orgId.isEmpty) {
      // Personal workspace - assume full permissions
      final capabilities = Capabilities(
        canRead: true,
        canWrite: true,
        canShare: true,
        canAdmin: true,
        canAnnotate: true,
        canEdit: true,
      );
      emit(PermissionLoaded(capabilities));
      return;
    }
    emit(PermissionLoading());
    try {
      final response = await apiClient.getRaw(
        '/orgs/${event.orgId}/permissions',
      );
      final capabilities = Capabilities(
        canRead: response['canRead'] ?? false,
        canWrite: response['canWrite'] ?? false,
        canShare: response['canShare'] ?? false,
        canAdmin: response['canAdmin'] ?? false,
        canAnnotate: response['canAnnotate'] ?? false,
        canEdit: response['canEdit'] ?? false,
      );
      emit(PermissionLoaded(capabilities));
    } catch (e) {
      emit(PermissionDenied(e.toString()));
    }
  }

  void _onPermissionsReset(
    PermissionsReset event,
    Emitter<PermissionState> emit,
  ) {
    emit(PermissionInitial());
  }
}
