import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:device_info_plus/device_info_plus.dart';
import 'package:package_info_plus/package_info_plus.dart';

import '../../marianumconnect_query.dart';

/// Submits user feedback to MarianumConnect (`POST me/feedback`, bearer-auth).
/// The optional screenshot is sent base64-encoded. Replaces the legacy mhsl.eu
/// `server/feedback` endpoint — the user no longer needs to be sent explicitly,
/// the bearer token identifies them.
class SubmitFeedback extends MarianumConnectQuery {
  SubmitFeedback({super.dio});

  Future<void> run({
    required String message,
    Uint8List? screenshot,
    String screenshotContentType = 'image/png',
  }) => guard(() async {
    final package = await PackageInfo.fromPlatform();
    final screenshotBase64 = screenshot != null ? base64Encode(screenshot) : null;
    await dio.post<void>(
      endpoint('me/feedback'),
      data: {
        'message': message,
        'screenshot': ?screenshotBase64,
        'screenshotContentType': screenshot != null ? screenshotContentType : null,
        'platform': _platform(),
        'appVersion': package.version,
        'appBuild': int.tryParse(package.buildNumber),
        'deviceModel': await _deviceModel(),
      },
    );
  });

  static String? _platform() {
    if (Platform.isAndroid) return 'android';
    if (Platform.isIOS) return 'ios';
    return null;
  }

  static Future<String?> _deviceModel() async {
    try {
      final info = DeviceInfoPlugin();
      if (Platform.isAndroid) return (await info.androidInfo).model;
      if (Platform.isIOS) return (await info.iosInfo).utsname.machine;
    } catch (_) {
      // Device-Plugin nicht verfügbar (z.B. Tests).
    }
    return null;
  }
}
