import { createMrtClient, DEFAULT_MRT_ORIGIN } from '../../clients/mrt.js';
import { getLogger } from '../../logging/logger.js';
/**
 * Lists redirects for an MRT environment.
 *
 * @param options - List options
 * @param auth - Authentication strategy (ApiKeyStrategy)
 * @returns Paginated list of redirects
 * @throws Error if request fails
 *
 * @example
 * ```typescript
 * import { ApiKeyStrategy } from '@salesforce/b2c-tooling-sdk/auth';
 * import { listRedirects } from '@salesforce/b2c-tooling-sdk/operations/mrt';
 *
 * const auth = new ApiKeyStrategy(process.env.MRT_API_KEY!, 'Authorization');
 *
 * const result = await listRedirects({
 *   projectSlug: 'my-storefront',
 *   targetSlug: 'staging'
 * }, auth);
 *
 * for (const redirect of result.redirects) {
 *   console.log(`${redirect.from_path} -> ${redirect.to_url}`);
 * }
 * ```
 */
export async function listRedirects(options, auth) {
    const logger = getLogger();
    const { projectSlug, targetSlug, limit, offset, search, ordering, origin } = options;
    logger.debug({ projectSlug, targetSlug }, '[MRT] Listing redirects');
    const client = createMrtClient({ origin: origin || DEFAULT_MRT_ORIGIN }, auth);
    const { data, error } = await client.GET('/api/projects/{project_slug}/target/{target_slug}/redirect/', {
        params: {
            path: { project_slug: projectSlug, target_slug: targetSlug },
            query: {
                limit,
                offset,
                search,
                ordering,
            },
        },
    });
    if (error) {
        const errorMessage = typeof error === 'object' && error !== null && 'message' in error
            ? String(error.message)
            : JSON.stringify(error);
        throw new Error(`Failed to list redirects: ${errorMessage}`);
    }
    logger.debug({ count: data.count }, '[MRT] Redirects listed');
    return {
        count: data.count ?? 0,
        next: data.next ?? null,
        previous: data.previous ?? null,
        redirects: data.results ?? [],
    };
}
/**
 * Creates a redirect for an MRT environment.
 *
 * @param options - Create redirect options
 * @param auth - Authentication strategy (ApiKeyStrategy)
 * @returns The created redirect
 * @throws Error if request fails
 *
 * @example
 * ```typescript
 * import { ApiKeyStrategy } from '@salesforce/b2c-tooling-sdk/auth';
 * import { createRedirect } from '@salesforce/b2c-tooling-sdk/operations/mrt';
 *
 * const auth = new ApiKeyStrategy(process.env.MRT_API_KEY!, 'Authorization');
 *
 * const redirect = await createRedirect({
 *   projectSlug: 'my-storefront',
 *   targetSlug: 'staging',
 *   fromPath: '/old-page',
 *   toUrl: '/new-page',
 *   httpStatusCode: 301
 * }, auth);
 * ```
 */
export async function createRedirect(options, auth) {
    const logger = getLogger();
    const { projectSlug, targetSlug, fromPath, toUrl, httpStatusCode, forwardQuerystring, forwardWildcard, origin } = options;
    logger.debug({ projectSlug, targetSlug, fromPath, toUrl }, '[MRT] Creating redirect');
    const client = createMrtClient({ origin: origin || DEFAULT_MRT_ORIGIN }, auth);
    const body = {
        from_path: fromPath,
        to_url: toUrl,
        http_status_code: httpStatusCode,
        forward_querystring: forwardQuerystring,
        forward_wildcard: forwardWildcard,
    };
    const { data, error } = await client.POST('/api/projects/{project_slug}/target/{target_slug}/redirect/', {
        params: {
            path: { project_slug: projectSlug, target_slug: targetSlug },
        },
        body,
    });
    if (error) {
        const errorMessage = typeof error === 'object' && error !== null && 'message' in error
            ? String(error.message)
            : JSON.stringify(error);
        throw new Error(`Failed to create redirect: ${errorMessage}`);
    }
    logger.debug({ fromPath }, '[MRT] Redirect created');
    return data;
}
/**
 * Gets a redirect from an MRT environment.
 *
 * @param options - Get redirect options
 * @param auth - Authentication strategy (ApiKeyStrategy)
 * @returns The redirect
 * @throws Error if request fails
 */
export async function getRedirect(options, auth) {
    const logger = getLogger();
    const { projectSlug, targetSlug, fromPath, origin } = options;
    logger.debug({ projectSlug, targetSlug, fromPath }, '[MRT] Getting redirect');
    const client = createMrtClient({ origin: origin || DEFAULT_MRT_ORIGIN }, auth);
    const { data, error } = await client.GET('/api/projects/{project_slug}/target/{target_slug}/redirect/{from_path}', {
        params: {
            path: { project_slug: projectSlug, target_slug: targetSlug, from_path: fromPath },
        },
    });
    if (error) {
        const errorMessage = typeof error === 'object' && error !== null && 'message' in error
            ? String(error.message)
            : JSON.stringify(error);
        throw new Error(`Failed to get redirect: ${errorMessage}`);
    }
    logger.debug({ fromPath }, '[MRT] Redirect retrieved');
    return data;
}
/**
 * Updates a redirect in an MRT environment.
 *
 * @param options - Update redirect options
 * @param auth - Authentication strategy (ApiKeyStrategy)
 * @returns The updated redirect
 * @throws Error if request fails
 */
export async function updateRedirect(options, auth) {
    const logger = getLogger();
    const { projectSlug, targetSlug, fromPath, toUrl, httpStatusCode, forwardQuerystring, forwardWildcard, origin } = options;
    logger.debug({ projectSlug, targetSlug, fromPath }, '[MRT] Updating redirect');
    const client = createMrtClient({ origin: origin || DEFAULT_MRT_ORIGIN }, auth);
    const body = {};
    if (toUrl !== undefined) {
        body.to_url = toUrl;
    }
    if (httpStatusCode !== undefined) {
        body.http_status_code = httpStatusCode;
    }
    if (forwardQuerystring !== undefined) {
        body.forward_querystring = forwardQuerystring;
    }
    if (forwardWildcard !== undefined) {
        body.forward_wildcard = forwardWildcard;
    }
    const { data, error } = await client.PATCH('/api/projects/{project_slug}/target/{target_slug}/redirect/{from_path}', {
        params: {
            path: { project_slug: projectSlug, target_slug: targetSlug, from_path: fromPath },
        },
        body,
    });
    if (error) {
        const errorMessage = typeof error === 'object' && error !== null && 'message' in error
            ? String(error.message)
            : JSON.stringify(error);
        throw new Error(`Failed to update redirect: ${errorMessage}`);
    }
    logger.debug({ fromPath }, '[MRT] Redirect updated');
    return data;
}
/**
 * Deletes a redirect from an MRT environment.
 *
 * @param options - Delete redirect options
 * @param auth - Authentication strategy (ApiKeyStrategy)
 * @throws Error if request fails
 */
export async function deleteRedirect(options, auth) {
    const logger = getLogger();
    const { projectSlug, targetSlug, fromPath, origin } = options;
    logger.debug({ projectSlug, targetSlug, fromPath }, '[MRT] Deleting redirect');
    const client = createMrtClient({ origin: origin || DEFAULT_MRT_ORIGIN }, auth);
    const { error } = await client.DELETE('/api/projects/{project_slug}/target/{target_slug}/redirect/{from_path}', {
        params: {
            path: { project_slug: projectSlug, target_slug: targetSlug, from_path: fromPath },
        },
    });
    if (error) {
        const errorMessage = typeof error === 'object' && error !== null && 'message' in error
            ? String(error.message)
            : JSON.stringify(error);
        throw new Error(`Failed to delete redirect: ${errorMessage}`);
    }
    logger.debug({ fromPath }, '[MRT] Redirect deleted');
}
/**
 * Clones redirects from one target to another.
 *
 * Important: When you clone redirects, you're replacing all redirects
 * in the destination target with all redirects from the source target.
 *
 * @param options - Clone redirects options
 * @param auth - Authentication strategy (ApiKeyStrategy)
 * @returns Result with cloned redirects
 * @throws Error if request fails
 *
 * @example
 * ```typescript
 * import { ApiKeyStrategy } from '@salesforce/b2c-tooling-sdk/auth';
 * import { cloneRedirects } from '@salesforce/b2c-tooling-sdk/operations/mrt';
 *
 * const auth = new ApiKeyStrategy(process.env.MRT_API_KEY!, 'Authorization');
 *
 * const result = await cloneRedirects({
 *   projectSlug: 'my-storefront',
 *   fromTargetSlug: 'staging',
 *   toTargetSlug: 'production'
 * }, auth);
 *
 * console.log(`Cloned ${result.count} redirects`);
 * ```
 */
export async function cloneRedirects(options, auth) {
    const logger = getLogger();
    const { projectSlug, fromTargetSlug, toTargetSlug, origin } = options;
    logger.debug({ projectSlug, fromTargetSlug, toTargetSlug }, '[MRT] Cloning redirects');
    const client = createMrtClient({ origin: origin || DEFAULT_MRT_ORIGIN }, auth);
    const { data, error } = await client.POST('/api/projects/{project_slug}/target/{to_target_slug}/redirect/clone/', {
        params: {
            path: { project_slug: projectSlug, to_target_slug: toTargetSlug },
        },
        body: {
            from_target_slug: fromTargetSlug,
        },
    });
    if (error) {
        const errorMessage = typeof error === 'object' && error !== null && 'message' in error
            ? String(error.message)
            : JSON.stringify(error);
        throw new Error(`Failed to clone redirects: ${errorMessage}`);
    }
    // The clone API may return a paginated response or just confirmation
    const responseData = data;
    logger.debug({ count: responseData.count }, '[MRT] Redirects cloned');
    return {
        count: responseData.count ?? 0,
        redirects: responseData.results ?? [],
    };
}
//# sourceMappingURL=redirect.js.map