import 'package:dio/dio.dart';
import '../models/rent_dto.dart';
import '../../domain/repositories/rent_repository.dart';

class RentRepositoryImpl implements RentRepository {
  final Dio _dio;
  static const String _baseEndpoint = '/rents';

  RentRepositoryImpl({required Dio dio}) : _dio = dio;

  @override
  Future<RentListResponse> getRents({
    int page = 1,
    int pageSize = 10,
    String? search,
    String? status,
    int? equipmentHistoryId,
  }) async {
    try {
      final queryParams = {
        'page': page,
        'page_size': pageSize,
        if (search != null) 'search': search,
        if (status != null) 'status': status,
        if (equipmentHistoryId != null) 'equipment_history_id': equipmentHistoryId,
      };

      final response = await _dio.get(
        _baseEndpoint,
        queryParameters: queryParams,
      );

      return RentListResponse.fromJson(response.data);
    } on DioException catch (e) {
      throw _handleError(e);
    }
  }

  @override
  Future<RentDto> getRent(int id) async {
    try {
      final response = await _dio.get('$_baseEndpoint/$id');
      return RentDto.fromJson(response.data);
    } on DioException catch (e) {
      throw _handleError(e);
    }
  }

  @override
  Future<RentDto> createRent(RentRequestDto request) async {
    try {
      final response = await _dio.post(
        _baseEndpoint,
        data: request.toJson(),
      );

      return RentDto.fromJson(response.data);
    } on DioException catch (e) {
      throw _handleError(e);
    }
  }

  @override
  Future<RentDto> updateRent(int id, RentUpdateRequestDto request) async {
    try {
      final response = await _dio.put(
        '$_baseEndpoint/$id',
        data: request.toJson(),
      );

      return RentDto.fromJson(response.data);
    } on DioException catch (e) {
      throw _handleError(e);
    }
  }

  @override
  Future<void> deleteRent(int id) async {
    try {
      await _dio.delete('$_baseEndpoint/$id');
    } on DioException catch (e) {
      throw _handleError(e);
    }
  }

  @override
  Future<RentListResponse> getActiveRents({
    int page = 1,
    int pageSize = 10,
  }) async {
    try {
      final response = await _dio.get(
        '$_baseEndpoint/active',
        queryParameters: {
          'page': page,
          'page_size': pageSize,
        },
      );

      return RentListResponse.fromJson(response.data);
    } on DioException catch (e) {
      throw _handleError(e);
    }
  }

  @override
  Future<RentListResponse> getOverdueRents({
    int page = 1,
    int pageSize = 10,
  }) async {
    try {
      final response = await _dio.get(
        '$_baseEndpoint/overdue',
        queryParameters: {
          'page': page,
          'page_size': pageSize,
        },
      );

      return RentListResponse.fromJson(response.data);
    } on DioException catch (e) {
      throw _handleError(e);
    }
  }

  @override
  Future<Map<String, dynamic>> getRentStats() async {
    try {
      final response = await _dio.get('$_baseEndpoint/stats');
      return response.data as Map<String, dynamic>;
    } on DioException catch (e) {
      throw _handleError(e);
    }
  }

  @override
  Future<RentDto> returnRent(int id, String returnDate) async {
    try {
      final response = await _dio.patch(
        '$_baseEndpoint/$id/return',
        data: {'return_date': returnDate},
      );

      return RentDto.fromJson(response.data);
    } on DioException catch (e) {
      throw _handleError(e);
    }
  }

  String _handleError(DioException e) {
    if (e.response != null) {
      final statusCode = e.response!.statusCode;
      final data = e.response!.data;
      
      if (data is Map && data.containsKey('message')) {
        return data['message'];
      }
      
      switch (statusCode) {
        case 400:
          return '잘못된 요청입니다.';
        case 401:
          return '인증이 필요합니다.';
        case 403:
          return '권한이 없습니다.';
        case 404:
          return '임대 정보를 찾을 수 없습니다.';
        case 409:
          return '중복된 임대 정보가 존재합니다.';
        case 500:
          return '서버 오류가 발생했습니다.';
        default:
          return '오류가 발생했습니다. (코드: $statusCode)';
      }
    }
    
    if (e.type == DioExceptionType.connectionTimeout) {
      return '연결 시간이 초과되었습니다.';
    } else if (e.type == DioExceptionType.connectionError) {
      return '네트워크 연결을 확인해주세요.';
    }
    
    return '알 수 없는 오류가 발생했습니다.';
  }
}