import 'dart:convert';
import 'dart:io';
import 'package:aman_kassa_flutter/core/base/base_service.dart';
import 'package:aman_kassa_flutter/core/models/nct_product.dart';
import 'package:http/http.dart' as http;
import 'package:http/io_client.dart';

class NctService extends BaseService {
  static const String _baseUrl = 'https://nct.gov.kz/api/integration/ofd/search_ofd/';

  Future<List<NctProduct>> searchByNtin(String ntin) async {
    final uri = Uri.parse(_baseUrl).replace(queryParameters: {'tin': ntin});
    log.i('NCT request: $uri');

    http.Client client = _buildClient();
    late http.Response response;
    try {
      response = await client.get(uri, headers: {'Accept': 'application/json'});
    } on TlsException catch (e) {
      log.e('NCT TLS error', e);
      throw NctServiceException('Ошибка SSL при подключении к NCT: ${e.message}');
    } on SocketException catch (e) {
      log.e('NCT network error', e);
      throw NctServiceException('Ошибка сети при подключении к NCT: ${e.message}');
    } catch (e) {
      log.e('NCT request error', e);
      throw NctServiceException('Ошибка запроса к NCT: $e');
    } finally {
      client.close();
    }

    log.i('NCT status: ${response.statusCode}');

    if (response.statusCode != 200) {
      throw NctServiceException('NCT вернул статус ${response.statusCode}');
    }

    try {
      final bodyString = utf8.decode(response.bodyBytes);
      log.i('NCT body: ${bodyString.length > 300 ? bodyString.substring(0, 300) : bodyString}');
      final decoded = json.decode(bodyString);
      List<dynamic> list;
      if (decoded is List) {
        list = decoded;
      } else if (decoded is Map && decoded.containsKey('results')) {
        list = decoded['results'] as List<dynamic>;
      } else {
        log.w('NCT unexpected response format: ${decoded.runtimeType}');
        return [];
      }
      return list
          .map((e) => NctProduct.fromJson(e as Map<String, dynamic>))
          .toList();
    } catch (e) {
      log.e('NCT JSON parse error', e);
      throw NctServiceException('Ошибка разбора ответа NCT: $e');
    }
  }

  http.Client _buildClient() {
    final httpClient = HttpClient()
      ..badCertificateCallback = (cert, host, port) {
        log.w('NCT bad certificate for $host:$port — subject: ${cert.subject}');
        return host == 'nct.gov.kz';
      };
    return IOClient(httpClient);
  }
}

class NctServiceException implements Exception {
  final String message;
  NctServiceException(this.message);
  @override
  String toString() => message;
}
