import 'package:dio/dio.dart';
import '../../core/constants/app_constants.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 perPage = AppConstants.rentPageSize,
    int? equipmentId,
    int? companyId,
    bool? isActive,
    DateTime? dateFrom,
    DateTime? dateTo,
  }) async {
    try {
      final queryParams = {
        'page': page,
        'per_page': perPage,
        if (equipmentId != null) 'equipment_id': equipmentId,
        if (companyId != null) 'company_id': companyId,
        if (isActive != null) 'is_active': isActive,
        if (dateFrom != null) 'date_from': dateFrom.toIso8601String().split('T')[0],
        if (dateTo != null) 'date_to': dateTo.toIso8601String().split('T')[0],
      };

      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<List<RentDto>> getActiveRents() async {
    try {
      final response = await _dio.get('$_baseEndpoint/active');
      
      // Backend returns List<RentDto> directly for /active endpoint
      final List<dynamic> dataList = response.data as List<dynamic>;
      return dataList.map((json) => RentDto.fromJson(json)).toList();
    } 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 '알 수 없는 오류가 발생했습니다.';
  }
}