import { isNothing } from "@jet/environment/types/optional";
import { appEventPageRoutes } from "../../common/product-page/intent-controller-routing";
import { injectSEOData } from "../../api/models/web-renderable-page";
import { makeAppEventPageRequest, makeShelfBasedAppEventDetailPage } from "../../common/app-events/app-events-common";
import { withActiveIntent } from "../../foundation/dependencies/active-intent";
import { fetchData, NetworkError } from "../../foundation/media/network";
import { URL } from "../../foundation/network/urls";
import { injectWebNavigation } from "../../common/web-navigation/inject-web-navigation";
import { validateAdamId } from "../../foundation/media/util";
export const AppEventPageIntentController = {
    $intentKind: "AppEventPageIntent",
    routes: appEventPageRoutes,
    async perform(intent, objectGraphWithoutActiveIntent) {
        return await withActiveIntent(objectGraphWithoutActiveIntent, intent, async (objectGraph) => {
            var _a;
            // See: https://github.pie.apple.com/its/Jingle/blob/ce14e21b6ac3dd4be884aa12b26d4e79c6d8aa7a/MZStorePlatform/src/main/java/com/apple/jingle/store/mediaapi/resource/SFMediaAPICommonResourceType.java#L50
            validateAdamId(objectGraph, intent.id);
            const mediaApiRequest = makeAppEventPageRequest(objectGraph, intent);
            const response = await fetchData(objectGraph, mediaApiRequest);
            const page = makeShelfBasedAppEventDetailPage(objectGraph, response);
            if (isNothing(page)) {
                const notFoundError = new NetworkError("Media API response lacked required data");
                notFoundError.statusCode = 404;
                throw notFoundError;
            }
            // The page URL (`.canonicalURL` property on the view-model) from Media API does not account for the `platform`
            // query param; we need to add that in ourselves. We can't rely on `makeCanonicalUrl` as that does not handle the
            // `appName` segment; we need to take the Media API URL and append the `platform` ourselves
            if (intent.platform && page.canonicalURL) {
                const pageURL = new URL(page.canonicalURL);
                pageURL.param("platform", intent.platform);
                page.canonicalURL = pageURL.toString();
            }
            if (objectGraph.client.isWeb) {
                injectWebNavigation(objectGraph, page, intent.platform);
                injectSEOData(page, (_a = objectGraph.seo) === null || _a === void 0 ? void 0 : _a.getSEODataForAppEventPage(objectGraph, page, response));
            }
            return page;
        });
    },
};
//# sourceMappingURL=app-event-page-intent-controller.js.map