import 'package:dartz/dartz.dart';
import 'package:injectable/injectable.dart';
import '../../../data/models/common/pagination_params.dart';
import '../../../data/models/license/license_dto.dart';
import '../../repositories/license_repository.dart';
import '../../../core/errors/failures.dart';
import '../base_usecase.dart';

/// 라이선스 목록 조회 UseCase
@injectable
class GetLicensesUseCase implements UseCase<LicenseListResponseDto, GetLicensesParams> {
  final LicenseRepository repository;

  GetLicensesUseCase(this.repository);

  @override
  Future<Either<Failure, LicenseListResponseDto>> call(GetLicensesParams params) async {
    try {
      final result = await repository.getLicenses(
        page: params.page,
        limit: params.perPage,
        search: params.search,
        companyId: params.filters?['companyId'],
        equipmentType: params.filters?['equipmentType'],
        expiryStatus: params.filters?['expiryStatus'],
        sortBy: params.filters?['sortBy'],
        sortOrder: params.filters?['sortOrder'],
      );
      return result.map((paginatedResponse) => LicenseListResponseDto(
        items: paginatedResponse.items.map((license) => LicenseDto(
          id: license.id ?? 0,
          licenseKey: license.licenseKey,
          productName: license.productName,
          vendor: license.vendor,
          licenseType: license.licenseType,
          userCount: license.userCount,
          purchaseDate: license.purchaseDate,
          expiryDate: license.expiryDate,
          purchasePrice: license.purchasePrice,
          companyId: license.companyId,
          branchId: license.branchId,
          assignedUserId: license.assignedUserId,
          remark: license.remark,
          isActive: license.isActive ?? true,
          createdAt: license.createdAt ?? DateTime.now(),
          updatedAt: license.updatedAt ?? DateTime.now(),
          companyName: license.companyName,
          branchName: license.branchName,
          assignedUserName: license.assignedUserName,
        )).toList(),
        page: paginatedResponse.page,
        perPage: params.perPage,
        total: paginatedResponse.totalElements,
        totalPages: paginatedResponse.totalPages,
      ));
    } catch (e) {
      return Left(ServerFailure(message: e.toString()));
    }
  }
}

/// 라이선스 목록 조회 파라미터
class GetLicensesParams {
  final int page;
  final int perPage;
  final String? search;
  final Map<String, dynamic>? filters;

  GetLicensesParams({
    this.page = 1,
    this.perPage = 20,
    this.search,
    this.filters,
  });

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