import { WITHDRAW_BALANCE_ROUTE } from "../constants.js";
import type { Config } from "../createConfig.js";
import type { BaseErrorType } from "../errors/base.js";
import { postRelayerWithAuth } from "../utils/http.js";
import { getWalletId } from "./getWalletId.js";

export type WithdrawRequestParameters = { request: string; mint: `0x${string}` };

export type WithdrawRequestReturnType = { taskId: string };

export type WithdrawRequestErrorType = BaseErrorType;

export async function withdrawRequest(
    config: Config,
    parameters: WithdrawRequestParameters,
): Promise<WithdrawRequestReturnType> {
    const { mint, request } = parameters;
    const { getBaseUrl } = config;

    const walletId = getWalletId(config);
    const logger = config.getLogger("core:actions:withdrawRequest");

    try {
        const res = await postRelayerWithAuth(
            config,
            getBaseUrl(WITHDRAW_BALANCE_ROUTE(walletId, mint)),
            request,
        );
        logger.debug(`task update-wallet(${res.task_id})`, {
            walletId,
            taskId: res.task_id,
        });
        return { taskId: res.task_id };
    } catch (error) {
        logger.error(
            `Withdraw request failed: ${error instanceof Error ? error.message : String(error)}`,
            { walletId },
        );
        throw error;
    }
}
