import { createMrtB2CClient, DEFAULT_MRT_B2C_ORIGIN, } from '../../clients/mrt-b2c.js';
import { getLogger } from '../../logging/logger.js';
const B2C_API_PATH = '/api/cc/b2c';
/**
 * Ensures the origin has the /api/cc/b2c path suffix.
 * When callers pass the generic MRT origin (e.g. https://cloud.mobify.com),
 * we need to append the B2C API path.
 */
function toB2COrigin(origin) {
    if (!origin)
        return DEFAULT_MRT_B2C_ORIGIN;
    // Already has the B2C path
    if (origin.endsWith(B2C_API_PATH))
        return origin;
    // Strip trailing slash before appending
    return origin.replace(/\/+$/, '') + B2C_API_PATH;
}
/**
 * Gets B2C Commerce info for an organization.
 *
 * Returns the list of B2C Commerce instances connected to the organization.
 *
 * @param options - Operation options
 * @param auth - Authentication strategy (ApiKeyStrategy)
 * @returns B2C organization info
 * @throws Error if request fails
 *
 * @example
 * ```typescript
 * import { ApiKeyStrategy } from '@salesforce/b2c-tooling-sdk/auth';
 * import { getB2COrgInfo } from '@salesforce/b2c-tooling-sdk/operations/mrt';
 *
 * const auth = new ApiKeyStrategy(process.env.MRT_API_KEY!, 'Authorization');
 *
 * const info = await getB2COrgInfo({
 *   organizationSlug: 'my-org'
 * }, auth);
 *
 * console.log(`B2C Customer: ${info.is_b2c_customer}`);
 * console.log(`Instances: ${info.instances.join(', ')}`);
 * ```
 */
export async function getB2COrgInfo(options, auth) {
    const logger = getLogger();
    const { organizationSlug, origin } = options;
    logger.debug({ organizationSlug }, '[MRT-B2C] Getting B2C organization info');
    const client = createMrtB2CClient({ origin: toB2COrigin(origin) }, auth);
    const { data, error } = await client.GET('/b2c-organization-info/{organization_slug}/', {
        params: {
            path: { organization_slug: organizationSlug },
        },
    });
    if (error) {
        const errorMessage = typeof error === 'object' && error !== null && 'message' in error
            ? String(error.message)
            : JSON.stringify(error);
        throw new Error(`Failed to get B2C organization info: ${errorMessage}`);
    }
    logger.debug({ isB2cCustomer: data.is_b2c_customer }, '[MRT-B2C] B2C organization info retrieved');
    return data;
}
/**
 * Gets B2C Commerce info for a target/environment.
 *
 * Returns the B2C Commerce instance and sites connected to the target.
 *
 * @param options - Operation options
 * @param auth - Authentication strategy (ApiKeyStrategy)
 * @returns B2C target info
 * @throws Error if request fails
 *
 * @example
 * ```typescript
 * import { ApiKeyStrategy } from '@salesforce/b2c-tooling-sdk/auth';
 * import { getB2CTargetInfo } from '@salesforce/b2c-tooling-sdk/operations/mrt';
 *
 * const auth = new ApiKeyStrategy(process.env.MRT_API_KEY!, 'Authorization');
 *
 * const info = await getB2CTargetInfo({
 *   projectSlug: 'my-storefront',
 *   targetSlug: 'production'
 * }, auth);
 *
 * console.log(`Instance: ${info.instance_id}`);
 * console.log(`Sites: ${info.sites?.join(', ')}`);
 * ```
 */
export async function getB2CTargetInfo(options, auth) {
    const logger = getLogger();
    const { projectSlug, targetSlug, origin } = options;
    logger.debug({ projectSlug, targetSlug }, '[MRT-B2C] Getting B2C target info');
    const client = createMrtB2CClient({ origin: toB2COrigin(origin) }, auth);
    const { data, error } = await client.GET('/projects/{project_slug}/b2c-target-info/{target_slug}/', {
        params: {
            path: { project_slug: projectSlug, target_slug: targetSlug },
        },
    });
    if (error) {
        const errorMessage = typeof error === 'object' && error !== null && 'message' in error
            ? String(error.message)
            : JSON.stringify(error);
        throw new Error(`Failed to get B2C target info: ${errorMessage}`);
    }
    logger.debug({ instanceId: data.instance_id }, '[MRT-B2C] B2C target info retrieved');
    return data;
}
/**
 * Sets (creates/replaces) B2C Commerce info for a target/environment.
 *
 * @param options - Operation options
 * @param auth - Authentication strategy (ApiKeyStrategy)
 * @returns Updated B2C target info
 * @throws Error if request fails
 *
 * @example
 * ```typescript
 * import { ApiKeyStrategy } from '@salesforce/b2c-tooling-sdk/auth';
 * import { setB2CTargetInfo } from '@salesforce/b2c-tooling-sdk/operations/mrt';
 *
 * const auth = new ApiKeyStrategy(process.env.MRT_API_KEY!, 'Authorization');
 *
 * const info = await setB2CTargetInfo({
 *   projectSlug: 'my-storefront',
 *   targetSlug: 'production',
 *   instanceId: 'aaaa_prd',
 *   sites: ['RefArch', 'SiteGenesis']
 * }, auth);
 *
 * console.log(`Connected to instance: ${info.instance_id}`);
 * ```
 */
export async function setB2CTargetInfo(options, auth) {
    const logger = getLogger();
    const { projectSlug, targetSlug, instanceId, sites, origin } = options;
    logger.debug({ projectSlug, targetSlug, instanceId }, '[MRT-B2C] Setting B2C target info');
    const client = createMrtB2CClient({ origin: toB2COrigin(origin) }, auth);
    const body = {
        instance_id: instanceId,
    };
    if (sites !== undefined) {
        body.sites = sites;
    }
    const { data, error } = await client.PUT('/projects/{project_slug}/b2c-target-info/{target_slug}/', {
        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 set B2C target info: ${errorMessage}`);
    }
    logger.debug({ instanceId: data.instance_id }, '[MRT-B2C] B2C target info set');
    return data;
}
/**
 * Updates B2C Commerce info for a target/environment.
 *
 * @param options - Operation options
 * @param auth - Authentication strategy (ApiKeyStrategy)
 * @returns Updated B2C target info
 * @throws Error if request fails
 *
 * @example
 * ```typescript
 * import { ApiKeyStrategy } from '@salesforce/b2c-tooling-sdk/auth';
 * import { updateB2CTargetInfo } from '@salesforce/b2c-tooling-sdk/operations/mrt';
 *
 * const auth = new ApiKeyStrategy(process.env.MRT_API_KEY!, 'Authorization');
 *
 * // Update only the sites list
 * const info = await updateB2CTargetInfo({
 *   projectSlug: 'my-storefront',
 *   targetSlug: 'production',
 *   sites: ['RefArch', 'SiteGenesis', 'NewSite']
 * }, auth);
 *
 * console.log(`Updated sites: ${info.sites?.join(', ')}`);
 * ```
 */
export async function updateB2CTargetInfo(options, auth) {
    const logger = getLogger();
    const { projectSlug, targetSlug, instanceId, sites, origin } = options;
    logger.debug({ projectSlug, targetSlug, instanceId }, '[MRT-B2C] Updating B2C target info');
    const client = createMrtB2CClient({ origin: toB2COrigin(origin) }, auth);
    const body = {};
    if (instanceId !== undefined) {
        body.instance_id = instanceId;
    }
    if (sites !== undefined) {
        body.sites = sites;
    }
    const { data, error } = await client.PATCH('/projects/{project_slug}/b2c-target-info/{target_slug}/', {
        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 update B2C target info: ${errorMessage}`);
    }
    logger.debug({ instanceId: data.instance_id }, '[MRT-B2C] B2C target info updated');
    return data;
}
//# sourceMappingURL=b2c-config.js.map