import 'package:get_it/get_it.dart';
import 'package:superport/core/constants/app_constants.dart';
import 'package:superport/core/errors/exceptions.dart';
import 'package:superport/core/errors/failures.dart';
import 'package:superport/data/datasources/remote/equipment_remote_datasource.dart';
import 'package:superport/data/models/common/paginated_response.dart';
import 'package:superport/data/models/equipment/equipment_dto.dart';
import 'package:superport/data/repositories/equipment_history_repository.dart';

class EquipmentService {
  final EquipmentRemoteDataSource _remoteDataSource = GetIt.instance<EquipmentRemoteDataSource>();
  final EquipmentHistoryRepository _historyRepository = GetIt.instance<EquipmentHistoryRepository>();

  // 장비 목록 조회 (간단한 버전)
  Future<PaginatedResponse<EquipmentDto>> getEquipments({
    int page = 1,
    int perPage = AppConstants.equipmentPageSize,
    String? search,
    int? companyId,
  }) async {
    try {
      final response = await _remoteDataSource.getEquipments(
        page: page,
        perPage: perPage,
        search: search,
        companyId: companyId,
      );

      return PaginatedResponse<EquipmentDto>(
        items: response.items,
        page: response.currentPage,
        size: response.pageSize ?? 20,
        totalElements: response.totalCount,
        totalPages: response.totalPages,
        first: response.currentPage == 1,
        last: response.currentPage >= response.totalPages,
      );
    } on ServerException catch (e) {
      throw ServerFailure(message: e.message);
    } catch (e) {
      throw ServerFailure(message: 'Failed to fetch equipments: $e');
    }
  }

  // 장비 상세 조회
  Future<EquipmentDto> getEquipmentDetail(int id) async {
    try {
      return await _remoteDataSource.getEquipmentDetail(id);
    } on ServerException catch (e) {
      throw ServerFailure(message: e.message);
    } catch (e) {
      throw ServerFailure(message: 'Failed to fetch equipment detail: $e');
    }
  }

  // 장비 생성
  Future<EquipmentDto> createEquipment(EquipmentRequestDto request) async {
    try {
      return await _remoteDataSource.createEquipment(request);
    } on ServerException catch (e) {
      throw ServerFailure(message: e.message);
    } catch (e) {
      throw ServerFailure(message: 'Failed to create equipment: $e');
    }
  }

  // 장비 수정
  Future<EquipmentDto> updateEquipment(int id, EquipmentUpdateRequestDto request) async {
    try {
      return await _remoteDataSource.updateEquipment(id, request);
    } on ServerException catch (e) {
      throw ServerFailure(message: e.message);
    } catch (e) {
      throw ServerFailure(message: 'Failed to update equipment: $e');
    }
  }

  // 장비 삭제
  Future<void> deleteEquipment(int id) async {
    try {
      await _remoteDataSource.deleteEquipment(id);
    } on ServerException catch (e) {
      throw ServerFailure(message: e.message);
    } catch (e) {
      throw ServerFailure(message: 'Failed to delete equipment: $e');
    }
  }

  // 상태별 장비 조회
  Future<PaginatedResponse<EquipmentDto>> getEquipmentsWithStatus({
    int page = 1,
    int perPage = AppConstants.equipmentPageSize,
    String? search,
    String? status,
    int? companyId,
  }) async {
    try {
      final response = await _remoteDataSource.getEquipments(
        page: page,
        perPage: perPage,
        search: search,
        companyId: companyId,
      );

      // 간단한 상태 필터링 (현재는 서버에서 상태 코드를 명확히 제공하지 않으므로 전체 반환)
      List<EquipmentDto> filteredItems = response.items;
      if (status != null && status.isNotEmpty) {
        filteredItems = response.items; // 서버 측 필터링으로 대체 예정
      }

      return PaginatedResponse<EquipmentDto>(
        items: filteredItems,
        page: response.currentPage,
        size: response.pageSize ?? perPage,
        // 메타 정보는 반드시 서버 응답을 신뢰 (현재 페이지 아이템 수가 아님)
        totalElements: response.totalCount,
        totalPages: response.totalPages,
        first: response.currentPage == 1,
        last: response.currentPage >= response.totalPages,
      );
    } on ServerException catch (e) {
      throw ServerFailure(message: e.message);
    } catch (e) {
      throw ServerFailure(message: 'Failed to fetch equipments with status: $e');
    }
  }

  // 장비 상태 변경 (백엔드 스키마에서는 단순히 업데이트)
  Future<EquipmentDto> changeEquipmentStatus(int id, String newStatus) async {
    try {
      // 백엔드 스키마에는 상태 필드가 없으므로 기본 업데이트 사용
      // 실제 구현에서는 백엔드의 실제 필드를 사용해야 함
      final equipment = await getEquipmentDetail(id);
      final request = EquipmentUpdateRequestDto(
        companiesId: equipment.companiesId,
        modelsId: equipment.modelsId,
        serialNumber: equipment.serialNumber,
        // 실제 백엔드 필드들만 사용
      );
      
      return await _remoteDataSource.updateEquipment(id, request);
    } on ServerException catch (e) {
      throw ServerFailure(message: e.message);
    } catch (e) {
      throw ServerFailure(message: 'Failed to change equipment status: $e');
    }
  }

  // 장비 이력 조회
  Future<List<dynamic>> getEquipmentHistory(int equipmentId, {int? page, int? perPage}) async {
    try {
      // 실제 EquipmentHistoryRepository를 통한 API 호출
      final histories = await _historyRepository.getEquipmentHistoriesByEquipmentId(equipmentId);
      return histories;
    } on ServerException catch (e) {
      throw ServerFailure(message: e.message);
    } catch (e) {
      throw ServerFailure(message: 'Failed to fetch equipment history: $e');
    }
  }
}
