import 'dart:convert';
import 'package:http/http.dart' as http;
import '../models/tailor_model.dart';
import '../utils/logger.dart';
import 'api_service.dart';

class SearchService {
  final String _baseUrl = ApiService.baseUrl.substring(0, ApiService.baseUrl.lastIndexOf('/api'));

  Future<List<TailorModel>> searchTailors(String query) async {
    try {
      AppLogger.info('Memulai pencarian penjahit', tag: 'SearchService');
      final endpoint = '$_baseUrl/api/tailors/search/name/$query';
      AppLogger.debug('URL: $endpoint', tag: 'SearchService');

      final response = await http.get(Uri.parse(endpoint)).timeout(
        const Duration(seconds: 5),
      );

      AppLogger.debug('Status code: ${response.statusCode}', tag: 'SearchService');
      AppLogger.debug('Response body: ${response.body}', tag: 'SearchService');

      if (response.statusCode == 200) {
        final Map<String, dynamic> responseData = json.decode(response.body);

        if (responseData['success'] == true && responseData['data'] != null) {
          final List<dynamic> tailorsData = responseData['data']['tailors'];
          final results =
              tailorsData.map((json) => TailorModel.fromJson(json)).toList();

          AppLogger.info(
              'Berhasil mendapatkan ${results.length} hasil pencarian',
              tag: 'SearchService');
          return results;
        } else {
          AppLogger.warning('Response sukses tapi tidak ada data penjahit',
              tag: 'SearchService');
          return [];
        }
      } else {
        AppLogger.error('Error searching tailors: ${response.statusCode}',
            error: response.body, tag: 'SearchService');
        throw Exception('Gagal mencari penjahit');
      }
    } on http.ClientException catch (e) {
      AppLogger.error('Client error while searching tailors',
          error: e.toString(), tag: 'SearchService');
      throw Exception('Terjadi kesalahan jaringan saat mencari penjahit');
    } on Exception catch (e) {
      AppLogger.error('Error while searching tailors',
          error: e.toString(), tag: 'SearchService');
      throw Exception('Terjadi kesalahan saat mencari penjahit');
    }
  }
}
