import 'package:dartz/dartz.dart';
import 'package:injectable/injectable.dart';
import '../../../core/constants/app_constants.dart';
import '../../../data/models/common/pagination_params.dart';
import '../../../data/models/warehouse/warehouse_location_dto.dart';
import '../../repositories/warehouse_location_repository.dart';
import '../../../core/errors/failures.dart';
import '../base_usecase.dart';

/// 창고 위치 목록 조회 UseCase
@injectable
class GetWarehouseLocationsUseCase implements UseCase<WarehouseLocationListResponse, GetWarehouseLocationsParams> {
  final WarehouseLocationRepository repository;

  GetWarehouseLocationsUseCase(this.repository);

  @override
  Future<Either<Failure, WarehouseLocationListResponse>> call(GetWarehouseLocationsParams params) async {
    try {
      final result = await repository.getWarehouseLocations(
        page: params.page,
        limit: params.perPage,
        search: params.search,
        locationType: params.filters?['locationType'],
        isActive: params.filters?['isActive'],
        hasEquipment: params.filters?['hasEquipment'],
        sortBy: params.filters?['sortBy'],
        sortOrder: params.filters?['sortOrder'],
      );
      return result.map((paginatedResponse) => WarehouseLocationListResponse(
        items: paginatedResponse.items.map((location) => WarehouseLocationDto(
          id: location.id,
          name: location.name,
          zipcodesZipcode: location.address, // Map address to zipcode
          remark: location.remark,
          registeredAt: DateTime.now(),
        )).toList(),
        currentPage: paginatedResponse.page,
        totalCount: paginatedResponse.totalElements,
        totalPages: paginatedResponse.totalPages,
        pageSize: params.perPage,
      ));
    } catch (e) {
      return Left(ServerFailure(message: e.toString()));
    }
  }
}

/// 창고 위치 목록 조회 파라미터
class GetWarehouseLocationsParams {
  final int page;
  final int perPage;
  final String? search;
  final Map<String, dynamic>? filters;

  GetWarehouseLocationsParams({
    this.page = 1,
    this.perPage = AppConstants.warehousePageSize,
    this.search,
    this.filters,
  });

  /// PaginationParams로부터 변환
  factory GetWarehouseLocationsParams.fromPaginationParams(PaginationParams params) {
    return GetWarehouseLocationsParams(
      page: params.page,
      perPage: params.perPage,
      search: params.search,
      filters: params.filters,
    );
  }
}