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

/// 창고 위치 수정 UseCase
@injectable
class UpdateWarehouseLocationUseCase implements UseCase<WarehouseLocationDto, UpdateWarehouseLocationParams> {
  final WarehouseLocationRepository repository;

  UpdateWarehouseLocationUseCase(this.repository);

  @override
  Future<Either<Failure, WarehouseLocationDto>> call(UpdateWarehouseLocationParams params) async {
    try {
      // 비즈니스 로직: 이름 유효성 검증
      if (params.name != null && params.name!.isEmpty) {
        return Left(ValidationFailure(message: '창고 위치 이름은 비어있을 수 없습니다'));
      }

      // 비즈니스 로직: 우편번호 유효성 검증
      if (params.zipcode != null && params.zipcode!.isEmpty) {
        return Left(ValidationFailure(message: '올바른 우편번호를 입력해주세요'));
      }

      final warehouseLocation = WarehouseLocation(
        id: params.id,
        name: params.name ?? '',
        address: params.zipcode ?? '', // Use zipcode as address
        remark: params.description,
      );

      final result = await repository.updateWarehouseLocation(params.id, warehouseLocation);
      return result.map((updatedLocation) => WarehouseLocationDto(
        id: updatedLocation.id,
        name: updatedLocation.name,
        zipcodesZipcode: params.zipcode,
        remark: params.description,
        updatedAt: DateTime.now(),
      ));
    } catch (e) {
      return Left(ServerFailure(message: e.toString()));
    }
  }
}

/// 창고 위치 수정 파라미터
class UpdateWarehouseLocationParams {
  final int id;
  final String? name;
  final String? zipcode;
  final String? description;

  UpdateWarehouseLocationParams({
    required this.id,
    this.name,
    this.zipcode,
    this.description,
  });

  Map<String, dynamic> toMap() {
    final Map<String, dynamic> data = {};
    if (name != null) data['Name'] = name;
    if (zipcode != null) data['zipcodes_zipcode'] = zipcode;
    if (description != null) data['Remark'] = description;
    return data;
  }
}