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 CreateWarehouseLocationUseCase implements UseCase<WarehouseLocationDto, CreateWarehouseLocationParams> {
  final WarehouseLocationRepository repository;

  CreateWarehouseLocationUseCase(this.repository);

  @override
  Future<Either<Failure, WarehouseLocationDto>> call(CreateWarehouseLocationParams params) async {
    try {
      // 비즈니스 로직: 이름 중복 체크
      if (params.name.isEmpty) {
        return Left(ValidationFailure(message: '창고 위치 이름은 필수입니다'));
      }

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

      final warehouseLocation = WarehouseLocation(
        id: 0, // Default id for new warehouse location
        name: params.name,
        address: params.zipcode ?? '', // Use zipcode as address
        remark: params.description,
      );

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

/// 창고 위치 생성 파라미터
class CreateWarehouseLocationParams {
  final String name;
  final String? zipcode;
  final String? description;

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

  Map<String, dynamic> toMap() {
    return {
      'Name': name,
      'zipcodes_zipcode': zipcode,
      'Remark': description,
    };
  }
}