import 'package:dartz/dartz.dart';
import 'package:injectable/injectable.dart';
import '../../../data/models/warehouse/warehouse_dto.dart';
import '../../../models/warehouse_location_model.dart';
import '../../../models/address_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.address.isEmpty) {
        return Left(ValidationFailure(message: '창고 주소는 필수입니다'));
      }

      // 비즈니스 로직: 연락처 형식 검증
      if (params.contactNumber != null && params.contactNumber!.isNotEmpty) {
        final phoneRegex = RegExp(r'^[\d\-\+\(\)\s]+$');
        if (!phoneRegex.hasMatch(params.contactNumber!)) {
          return Left(ValidationFailure(message: '올바른 연락처 형식이 아닙니다'));
        }
      }

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

      final result = await repository.createWarehouseLocation(warehouseLocation);
      return result.map((createdLocation) => WarehouseLocationDto(
        id: createdLocation.id ?? 0,
        name: createdLocation.name,
        address: createdLocation.address,
        isActive: true, // Default value since model doesn't have isActive
        createdAt: DateTime.now(), // Add required createdAt parameter
      ));
    } catch (e) {
      return Left(ServerFailure(message: e.toString()));
    }
  }
}

/// 창고 위치 생성 파라미터
class CreateWarehouseLocationParams {
  final String name;
  final String address;
  final String? description;
  final String? contactNumber;
  final String? manager;
  final double? latitude;
  final double? longitude;

  CreateWarehouseLocationParams({
    required this.name,
    required this.address,
    this.description,
    this.contactNumber,
    this.manager,
    this.latitude,
    this.longitude,
  });

  Map<String, dynamic> toMap() {
    return {
      'name': name,
      'address': address,
      'description': description,
      'contact_number': contactNumber,
      'manager': manager,
      'latitude': latitude,
      'longitude': longitude,
    };
  }
}