import { definePlugin, createPaginatedPluginMethod, } from "../../../utils/plugin-utils";
import { ListTriggerInboxMessagesSchema, ListTriggerInboxMessagesApiResponseSchema, TriggerMessageItemSchema, } from "./schemas";
import { triggerInboxResolver } from "../../../resolvers";
import { resolveTriggerInboxId } from "../utils";
import { DEFAULT_PAGE_SIZE } from "../../../constants";
import { triggersDefaults } from "../shared";
function extractNextCursor(next) {
    if (!next)
        return undefined;
    try {
        const url = new URL(next);
        return url.searchParams.get("cursor") ?? undefined;
    }
    catch {
        return undefined;
    }
}
export const listTriggerInboxMessagesPlugin = definePlugin((sdk) => createPaginatedPluginMethod(sdk, {
    ...triggersDefaults,
    name: "listTriggerInboxMessages",
    type: "list",
    itemType: "TriggerMessage",
    inputSchema: ListTriggerInboxMessagesSchema,
    outputSchema: TriggerMessageItemSchema,
    defaultPageSize: DEFAULT_PAGE_SIZE,
    resolvers: { inbox: triggerInboxResolver },
    handler: async ({ sdk, options }) => {
        const { inbox, cursor, pageSize } = options;
        const inboxId = await resolveTriggerInboxId({
            api: sdk.context.api,
            inbox,
        });
        const searchParams = {};
        if (pageSize !== undefined) {
            searchParams.limit = pageSize.toString();
        }
        if (cursor) {
            searchParams.cursor = cursor;
        }
        const rawResponse = await sdk.context.api.get(`/trigger-inbox/api/v1/inboxes/${encodeURIComponent(inboxId)}/messages`, { searchParams, authRequired: true });
        const response = ListTriggerInboxMessagesApiResponseSchema.parse(rawResponse);
        return {
            data: response.results,
            next: response.next ?? null,
        };
    },
    extractCursor: (response) => extractNextCursor(response.next),
}));
