import { b as generateId } from "./dist-uUUuTqM0.js";
import { m as actions } from "./module-RiCpyFsE.js";
import { a as addTransaction } from "./creators-1UUtt16O.js";
import { m as actions$1 } from "./module-DJjNH-7f.js";
import { r as dispatchActions, t as addDocument } from "./dist-mx7YTOSV.js";
import { t as alchemyIntegration } from "./alchemyIntegration-DsK1H6XE.js";
//#region editors/accounts-editor/services/accountTransactionsService.ts
var AccountTransactionsService = class {
	constructor() {}
	/**
	* Create an Account Transactions document and fetch transactions for the account
	*/
	async createAccountTransactionsDocument(account, accountsDocumentId, driveId) {
		try {
			if (!driveId) throw new Error("Drive ID is required to create document");
			const documentName = `${account.name} Transactions`;
			console.log("[AccountTransactionsService] Creating document:", {
				name: documentName,
				driveId
			});
			const createdNode = await addDocument(driveId, documentName, "powerhouse/account-transactions", void 0, void 0, void 0, "powerhouse-account-transactions-editor");
			if (!createdNode?.id) throw new Error("Failed to create AccountTransactions document");
			console.log("[AccountTransactionsService] Document created:", createdNode.id);
			await new Promise((resolve) => setTimeout(resolve, 500));
			await dispatchActions([actions.setAccount({
				id: account.id,
				account: account.account,
				name: account.name
			})], createdNode.id);
			console.log("[AccountTransactionsService] Account info set");
			await new Promise((resolve) => setTimeout(resolve, 200));
			let transactionsAdded = 0;
			try {
				console.log("[AccountTransactionsService] Fetching transactions from Alchemy for:", account.account);
				const result = await alchemyIntegration.getTransactionsFromAlchemy(account.account);
				console.log("[AccountTransactionsService] Alchemy result:", result.success, "transactions count:", result.transactions?.length || 0);
				if (result.success && result.transactions.length > 0) {
					const transactionActions = result.transactions.filter((txData) => {
						if (!txData.direction || !txData.from || !txData.to) {
							console.error(`[AccountTransactionsService] Skipping invalid transaction:`, txData);
							return false;
						}
						return true;
					}).map((txData) => {
						let amount;
						if (typeof txData.amount === "string") {
							const amountParts = txData.amount.split(" ");
							amount = {
								value: amountParts[0] || "0",
								unit: amountParts[1] || txData.token
							};
						} else if (typeof txData.amount === "object" && txData.amount && "value" in txData.amount && "unit" in txData.amount) amount = txData.amount;
						else amount = {
							value: "0",
							unit: txData.token
						};
						return addTransaction({
							id: generateId(),
							counterParty: txData.counterParty,
							amount,
							datetime: txData.datetime,
							txHash: txData.txHash,
							token: txData.token,
							blockNumber: txData.blockNumber,
							accountingPeriod: txData.accountingPeriod,
							direction: txData.direction || "OUTFLOW",
							budget: null
						});
					});
					console.log("[AccountTransactionsService] Creating", transactionActions.length, "transaction actions");
					if (transactionActions.length > 0) {
						console.log("[AccountTransactionsService] Dispatching", transactionActions.length, "transaction actions to document:", createdNode.id);
						const BATCH_SIZE = 100;
						for (let i = 0; i < transactionActions.length; i += BATCH_SIZE) try {
							const result = await dispatchActions(transactionActions.slice(i, i + BATCH_SIZE), createdNode.id);
							if (i === 0) console.log(`[AccountTransactionsService] First batch dispatch result:`, result);
							console.log(`[AccountTransactionsService] Dispatched batch ${Math.floor(i / BATCH_SIZE) + 1}/${Math.ceil(transactionActions.length / BATCH_SIZE)} (${Math.min(i + BATCH_SIZE, transactionActions.length)}/${transactionActions.length} transactions)`);
						} catch (dispatchError) {
							console.error(`[AccountTransactionsService] ERROR dispatching batch starting at ${i}:`, dispatchError);
							throw dispatchError;
						}
						transactionsAdded = transactionActions.length;
						console.log(`[AccountTransactionsService] Successfully dispatched all ${transactionsAdded} transaction actions`);
					}
				} else console.log("[AccountTransactionsService] No transactions to add:", result.success ? "success but empty" : "failed");
			} catch (alchemyError) {
				console.error("[AccountTransactionsService] ERROR fetching transactions from Alchemy:", alchemyError);
			}
			console.log("[AccountTransactionsService] Updating account in Accounts document:", {
				accountId: account.id,
				accountsDocumentId,
				transactionsDocId: createdNode.id
			});
			try {
				await dispatchActions([actions$1.updateAccount({
					id: account.id,
					accountTransactionsId: createdNode.id
				})], accountsDocumentId);
				console.log("[AccountTransactionsService] Successfully updated account with transactions ID");
			} catch (updateError) {
				console.error("[AccountTransactionsService] ERROR updating account:", updateError);
				throw updateError;
			}
			return {
				success: true,
				documentId: createdNode.id,
				transactionsAdded,
				message: `Successfully created document and fetched ${transactionsAdded} transactions`
			};
		} catch (error) {
			console.error("[AccountTransactionsService] Error creating account transactions:", error);
			return {
				success: false,
				message: `Failed to create account transactions: ${error instanceof Error ? error.message : "Unknown error"}`
			};
		}
	}
	/**
	* Sync transactions for an existing Account Transactions document
	* This fetches new transactions from Alchemy and adds them to an existing document
	*/
	async syncTransactionsForDocument(documentId, address) {
		try {
			console.log("[AccountTransactionsService] Syncing transactions for document:", documentId);
			const result = await alchemyIntegration.getTransactionsFromAlchemy(address);
			if (!result.success || result.transactions.length === 0) return {
				success: true,
				transactionsAdded: 0,
				message: "No new transactions found"
			};
			const transactionActions = result.transactions.filter((txData) => {
				if (!txData.direction || !txData.from || !txData.to) {
					console.error(`[AccountTransactionsService] Skipping invalid transaction:`, txData);
					return false;
				}
				return true;
			}).map((txData) => {
				let amount;
				if (typeof txData.amount === "string") {
					const amountParts = txData.amount.split(" ");
					amount = {
						value: amountParts[0] || "0",
						unit: amountParts[1] || txData.token
					};
				} else if (typeof txData.amount === "object" && txData.amount && "value" in txData.amount && "unit" in txData.amount) amount = txData.amount;
				else amount = {
					value: "0",
					unit: txData.token
				};
				return addTransaction({
					id: generateId(),
					counterParty: txData.counterParty,
					amount,
					datetime: txData.datetime,
					txHash: txData.txHash,
					token: txData.token,
					blockNumber: txData.blockNumber,
					accountingPeriod: txData.accountingPeriod,
					direction: txData.direction || "OUTFLOW",
					budget: null
				});
			});
			if (transactionActions.length > 0) {
				const BATCH_SIZE = 100;
				for (let i = 0; i < transactionActions.length; i += BATCH_SIZE) {
					await dispatchActions(transactionActions.slice(i, i + BATCH_SIZE), documentId);
					console.log(`[AccountTransactionsService] Synced batch ${Math.floor(i / BATCH_SIZE) + 1}/${Math.ceil(transactionActions.length / BATCH_SIZE)} (${Math.min(i + BATCH_SIZE, transactionActions.length)}/${transactionActions.length} transactions)`);
				}
				console.log(`[AccountTransactionsService] Successfully synced all ${transactionActions.length} transactions`);
			}
			return {
				success: true,
				transactionsAdded: transactionActions.length,
				message: `Successfully synced ${transactionActions.length} new transaction(s)`
			};
		} catch (error) {
			console.error("[AccountTransactionsService] Error syncing transactions:", error);
			return {
				success: false,
				transactionsAdded: 0,
				message: `Failed to sync transactions: ${error instanceof Error ? error.message : "Unknown error"}`
			};
		}
	}
};
const accountTransactionsService = new AccountTransactionsService();
//#endregion
export { accountTransactionsService as t };

//# sourceMappingURL=accountTransactionsService-DL9yTuR9.js.map