import 'package:dartz/dartz.dart';
import '../../../core/errors/failures.dart';
import '../../../core/utils/hierarchy_validator.dart';
import '../../../models/company_model.dart';
import '../../repositories/company_repository.dart';
import '../base_usecase.dart';
import '../../../data/models/company/company_dto.dart';

/// 부모 회사 변경 파라미터
class UpdateParentCompanyParams {
  final int companyId;
  final int? newParentId;

  const UpdateParentCompanyParams({
    required this.companyId,
    required this.newParentId,
  });
}

/// 부모 회사 변경 UseCase
class UpdateParentCompanyUseCase extends UseCase<Company, UpdateParentCompanyParams> {
  // 레포지토리 기반으로 마이그레이션
  final CompanyRepository _companyRepository;

  UpdateParentCompanyUseCase(this._companyRepository);

  @override
  Future<Either<Failure, Company>> call(UpdateParentCompanyParams params) async {
    try {
      // 1. 모든 회사 조회 (검증용)
      final allCompaniesEither = await _companyRepository.getCompanyHierarchy(includeInactive: true);
      
      // CompanyDto 리스트로 변환 (검증용)
      final companyResponses = allCompaniesEither.getOrElse(() => <Company>[]).map((company) => CompanyDto(
        id: company.id ?? 0,
        name: company.name,
        address: company.address.toString(),
        contactName: company.contactName ?? '',
        contactPhone: company.contactPhone ?? '',
        contactEmail: company.contactEmail ?? '',
        isActive: true,
        parentCompanyId: company.parentCompanyId,
        registeredAt: DateTime.now(),
      )).toList();
      
      // 2. 순환 참조 검증
      final circularValidation = HierarchyValidator.validateCircularReference(
        companyId: params.companyId,
        newParentId: params.newParentId,
        allCompanies: companyResponses,
      );
      
      if (!circularValidation.isValid) {
        return Left(ValidationFailure(
          message: circularValidation.message,
        ));
      }
      
      // 3. 계층 깊이 검증
      final depthValidation = HierarchyValidator.validateDepth(
        parentId: params.newParentId,
        allCompanies: companyResponses,
      );
      
      if (!depthValidation.isValid) {
        return Left(ValidationFailure(
          message: depthValidation.message,
        ));
      }
      
      // 4. 부모 변경 가능 여부 전체 검증
      final changeValidation = HierarchyValidator.validateParentChange(
        companyId: params.companyId,
        newParentId: params.newParentId,
        allCompanies: companyResponses,
      );
      
      if (!changeValidation.isValid) {
        return Left(ValidationFailure(
          message: changeValidation.message,
        ));
      }
      
      // 5~7. 레포지토리 메서드로 부모 변경 수행
      final updateEither = await _companyRepository.updateParentCompany(
        params.companyId,
        params.newParentId,
      );
      return updateEither;
    } on ServerFailure catch (e) {
      return Left(ServerFailure(
        message: e.message,
        originalError: e,
      ));
    } catch (e) {
      return Left(UnknownFailure(
        message: '부모 회사 변경 중 오류가 발생했습니다.',
        originalError: e,
      ));
    }
  }
}
