import 'package:dio/dio.dart';
import 'package:injectable/injectable.dart';
import 'package:superport/core/constants/api_endpoints.dart';
import 'package:superport/data/datasources/remote/api_client.dart';
import 'package:superport/data/models/vendor_dto.dart';
import 'package:superport/core/constants/app_constants.dart';

abstract class VendorRepository {
  Future<VendorListResponse> getAll({
    int page = 1,
    int limit = AppConstants.vendorPageSize,
    String? search,
    bool? isActive,
  });
  Future<VendorDto> getById(int id);
  Future<VendorDto> create(VendorDto vendor);
  Future<VendorDto> update(int id, VendorDto vendor);
  Future<void> delete(int id);
  Future<void> restore(int id);
}

@Injectable(as: VendorRepository)
class VendorRepositoryImpl implements VendorRepository {
  final ApiClient _apiClient;

  VendorRepositoryImpl(this._apiClient);

  @override
  Future<VendorListResponse> getAll({
    int page = 1,
    int limit = AppConstants.vendorPageSize,
    String? search,
    bool? isActive,
  }) async {
    try {
      final queryParams = <String, dynamic>{
        'page': page,
        'page_size': limit,
        'include_deleted': false, // 삭제된 벤더 제외
      };

      if (search != null && search.isNotEmpty) {
        queryParams['search'] = search;
      }
      if (isActive != null) {
        queryParams['is_active'] = isActive;
      }

      final response = await _apiClient.dio.get(
        ApiEndpoints.vendors,
        queryParameters: queryParams,
      );

      // API 응답 구조에 따라 파싱
      if (response.data is Map<String, dynamic>) {
        // 페이지네이션 응답 형식
        return VendorListResponse.fromJson(response.data);
      } else if (response.data is List) {
        // 배열 직접 반환 형식
        final vendors = (response.data as List)
            .map((json) => VendorDto.fromJson(json))
            .toList();
        return VendorListResponse(
          items: vendors,
          totalCount: vendors.length,
          currentPage: page,
          totalPages: 1,
        );
      } else {
        throw Exception('Unexpected response format');
      }
    } on DioException catch (e) {
      throw _handleError(e);
    }
  }

  @override
  Future<VendorDto> getById(int id) async {
    try {
      final response = await _apiClient.dio.get(
        '${ApiEndpoints.vendors}/$id',
      );
      return VendorDto.fromJson(response.data);
    } on DioException catch (e) {
      throw _handleError(e);
    }
  }

  @override
  Future<VendorDto> create(VendorDto vendor) async {
    try {
      final response = await _apiClient.dio.post(
        ApiEndpoints.vendors,
        data: vendor.toJson(),
      );
      return VendorDto.fromJson(response.data);
    } on DioException catch (e) {
      throw _handleError(e);
    }
  }

  @override
  Future<VendorDto> update(int id, VendorDto vendor) async {
    try {
      final response = await _apiClient.dio.put(
        '${ApiEndpoints.vendors}/$id',
        data: vendor.toJson(),
      );
      return VendorDto.fromJson(response.data);
    } on DioException catch (e) {
      throw _handleError(e);
    }
  }

  @override
  Future<void> delete(int id) async {
    try {
      await _apiClient.dio.delete(
        '${ApiEndpoints.vendors}/$id',
      );
    } on DioException catch (e) {
      throw _handleError(e);
    }
  }

  @override
  Future<void> restore(int id) async {
    try {
      await _apiClient.dio.put(
        '${ApiEndpoints.vendors}/$id/restore',
      );
    } on DioException catch (e) {
      throw _handleError(e);
    }
  }


  Exception _handleError(DioException e) {
    switch (e.type) {
      case DioExceptionType.connectionTimeout:
      case DioExceptionType.sendTimeout:
      case DioExceptionType.receiveTimeout:
        return Exception('연결 시간이 초과되었습니다.');
      case DioExceptionType.badResponse:
        final statusCode = e.response?.statusCode;
        final message = e.response?.data?['message'] ?? '서버 오류가 발생했습니다.';
        return Exception('[$statusCode] $message');
      case DioExceptionType.connectionError:
        return Exception('네트워크 연결을 확인해주세요.');
      default:
        return Exception('알 수 없는 오류가 발생했습니다.');
    }
  }
}