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

import 'package:flutter/material.dart';
import 'package:hl_lieferservice/dto/scan_response.dart';
import 'package:http/http.dart' as http;
import '../../../util.dart';
import '../../authentication/exceptions.dart';

class ScanService {
  Future<void> scanArticle(String internalId) async {
    try {
      var response = await http.post(
        urlBuilder("_web_scanArticle"),
        headers: getSessionOrThrow(),
        body: {"internal_id": internalId},
      );

      debugPrint(jsonEncode({"internal_id": internalId}));

      if (response.statusCode == HttpStatus.unauthorized) {
        throw UserUnauthorized();
      }

      Map<String, dynamic> responseJson = jsonDecode(response.body);
      debugPrint(responseJson.toString());
      ScanResponseDTO responseDto = ScanResponseDTO.fromJson(
        responseJson,
      );

      if (responseDto.succeeded == true) {
        return;
      } else {
        debugPrint("ERROR: ${responseDto.message}");
        throw responseDto.message;
      }
    } catch (e) {
      rethrow;
    }
  }
}