"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CreateWalletUseCase = void 0;
const uuid_1 = require("uuid");
const wallet_1 = require("../../../domain/entities/wallet");
const address_1 = require("../../../domain/entities/address");
const not_found_error_1 = require("../../../domain/errors/not-found-error");
const validation_error_1 = require("../../../domain/errors/validation-error");
class CreateWalletUseCase {
    walletRepository;
    deviceRepository;
    addressRepository;
    networkRepository;
    encryptionService;
    addressGenerator;
    constructor(walletRepository, deviceRepository, addressRepository, networkRepository, encryptionService, addressGenerator) {
        this.walletRepository = walletRepository;
        this.deviceRepository = deviceRepository;
        this.addressRepository = addressRepository;
        this.networkRepository = networkRepository;
        this.encryptionService = encryptionService;
        this.addressGenerator = addressGenerator;
    }
    async execute(input) {
        for (const deviceId of input.deviceIds) {
            const device = await this.deviceRepository.findById(deviceId);
            if (!device) {
                throw new not_found_error_1.NotFoundError('Device', deviceId);
            }
        }
        const encryptedPhrase = this.encryptionService.encrypt(input.phrase);
        if (!encryptedPhrase) {
            throw new validation_error_1.ValidationError('Failed to encrypt wallet phrase');
        }
        for (const deviceId of input.deviceIds) {
            const existing = await this.walletRepository.findByDeviceIdAndName(deviceId, input.name);
            if (existing) {
                throw new validation_error_1.ValidationError(`Wallet with name "${input.name}" already exists for this device`);
            }
        }
        const wallet = wallet_1.Wallet.create((0, uuid_1.v4)(), input.name, input.syncType, encryptedPhrase, input.deviceIds);
        const savedWallet = await this.walletRepository.save(wallet);
        const activeNetworks = await this.networkRepository.findActive();
        const addressTypes = new Set();
        for (const network of activeNetworks) {
            if (addressTypes.has(network.addressType)) {
                continue;
            }
            addressTypes.add(network.addressType);
            const generated = this.addressGenerator.generate(network, savedWallet);
            const address = address_1.Address.create((0, uuid_1.v4)(), generated.address, generated.type, savedWallet.id, false);
            await this.addressRepository.save(address);
        }
        return savedWallet;
    }
}
exports.CreateWalletUseCase = CreateWalletUseCase;
//# sourceMappingURL=create-wallet.use-case.js.map