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

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

  GetWarehouseLocationsUseCase(this.repository);

  @override
  Future<Either<Failure, WarehouseLocationListDto>> 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) => WarehouseLocationListDto(
        items: paginatedResponse.items.map((location) => WarehouseLocationDto(
          id: location.id ?? 0,
          name: location.name,
          address: location.address.toString(),
          isActive: true, // Default value since model doesn't have isActive
          createdAt: DateTime.now(), // Add required createdAt parameter
        )).toList(),
        page: paginatedResponse.page,
        perPage: params.perPage, // Add missing required perPage parameter
        total: paginatedResponse.totalElements,
        totalPages: paginatedResponse.totalPages,
      ));
    } 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 = 20,
    this.search,
    this.filters,
  });

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