import { definePlugin, createPaginatedPluginMethod, } from "../../../utils/plugin-utils";
import { ListTriggerInboxesSchema, ListTriggerInboxesApiResponseSchema, TriggerInboxItemSchema, } from "./schemas";
import { DEFAULT_PAGE_SIZE } from "../../../constants";
import { triggersDefaults } from "../shared";
function extractNextOffset(next) {
    if (!next)
        return undefined;
    try {
        const url = new URL(next);
        const offset = url.searchParams.get("offset");
        return offset || undefined;
    }
    catch {
        return undefined;
    }
}
export const listTriggerInboxesPlugin = definePlugin((sdk) => createPaginatedPluginMethod(sdk, {
    ...triggersDefaults,
    name: "listTriggerInboxes",
    type: "list",
    itemType: "TriggerInbox",
    inputSchema: ListTriggerInboxesSchema,
    outputSchema: TriggerInboxItemSchema,
    defaultPageSize: DEFAULT_PAGE_SIZE,
    handler: async ({ sdk, options }) => {
        const { api } = sdk.context;
        const searchParams = {};
        if (options.pageSize !== undefined) {
            searchParams.limit = options.pageSize.toString();
        }
        if (options.cursor) {
            searchParams.offset = options.cursor;
        }
        if (options.status) {
            searchParams.status = options.status;
        }
        if (options.name) {
            searchParams.name = options.name;
        }
        const rawResponse = await api.get("/trigger-inbox/api/v1/inboxes", {
            searchParams,
            authRequired: true,
        });
        const response = ListTriggerInboxesApiResponseSchema.parse(rawResponse);
        return {
            data: response.results,
            next: response.next ?? null,
        };
    },
    extractCursor: (response) => extractNextOffset(response.next),
}));
