import 'package:dio/dio.dart';
import 'package:flutter_test/flutter_test.dart';

import 'package:minstrel/api/errors.dart';

void main() {
  RequestOptions opts() => RequestOptions(path: '/x');

  group('ApiError.fromDio', () {
    test('flat envelope: {error: "code"}', () {
      final d = DioException(
        requestOptions: opts(),
        response: Response(
          requestOptions: opts(),
          statusCode: 503,
          data: {'error': 'lidarr_unreachable'},
        ),
      );
      final e = ApiError.fromDio(d);
      expect(e.code, 'lidarr_unreachable');
      expect(e.status, 503);
    });

    test('nested envelope: {error: {code, message}}', () {
      final d = DioException(
        requestOptions: opts(),
        response: Response(
          requestOptions: opts(),
          statusCode: 400,
          data: {'error': {'code': 'bad_request', 'message': 'invalid JSON body'}},
        ),
      );
      final e = ApiError.fromDio(d);
      expect(e.code, 'bad_request');
      expect(e.message, 'invalid JSON body');
    });

    test('connection refused: code is connection_refused', () {
      final d = DioException(
        requestOptions: opts(),
        type: DioExceptionType.connectionError,
        error: 'Connection refused',
      );
      final e = ApiError.fromDio(d);
      expect(e.code, 'connection_refused');
    });

    test('401 with no envelope falls back to unauthenticated', () {
      final d = DioException(
        requestOptions: opts(),
        response: Response(requestOptions: opts(), statusCode: 401),
      );
      final e = ApiError.fromDio(d);
      expect(e.code, 'unauthenticated');
    });
  });
}
