import { definePlugin } from "../../../utils/plugin-utils";
import { createPaginatedPluginMethod } from "../../../utils/plugin-utils";
import { ListTablesApiResponseSchema, ListTablesOptionsSchema, TableItemSchema, } from "./schemas";
import { extractCursor } from "../../../utils/function-utils";
import { ZapierValidationError } from "../../../types/errors";
import { transformTableItem } from "../utils";
import { DEFAULT_PAGE_SIZE } from "../../../constants";
import { tablesDefaults } from "../shared";
export const listTablesPlugin = definePlugin((sdk) => createPaginatedPluginMethod(sdk, {
    ...tablesDefaults,
    name: "listTables",
    type: "list",
    itemType: "Table",
    inputSchema: ListTablesOptionsSchema,
    outputSchema: TableItemSchema,
    defaultPageSize: DEFAULT_PAGE_SIZE,
    handler: async ({ sdk, options }) => {
        if (options.includeShared) {
            await sdk.context.checkCapability("canIncludeSharedTables");
        }
        const { api } = sdk.context;
        const searchParams = {};
        if (options.pageSize !== undefined) {
            searchParams.limit = options.pageSize.toString();
        }
        const tableIds = "tables" in options && options.tables
            ? options.tables
            : options.tableIds;
        if (tableIds && tableIds.length > 0) {
            searchParams.ids = tableIds.join(",");
        }
        if (options.kind) {
            searchParams.kind = options.kind;
        }
        if (options.search) {
            searchParams.q = options.search;
        }
        if (options.owner && options.owner !== "me" && !options.includeShared) {
            throw new ZapierValidationError('The "owner" option requires "includeShared" to be true. Without includeShared, only your own tables are returned.');
        }
        const owner = options.includeShared ? options.owner : "me";
        if (owner) {
            if (owner === "me") {
                const profile = await api.get("/zapier/api/v4/profile/", {
                    authRequired: true,
                });
                searchParams.owner_customuser_id = String(profile.id);
            }
            else {
                searchParams.owner_customuser_id = owner;
            }
        }
        if (options.cursor) {
            searchParams.offset = options.cursor;
        }
        const rawResponse = await api.get("/tables/api/v1/tables", {
            searchParams,
            authRequired: true,
        });
        const response = ListTablesApiResponseSchema.parse(rawResponse);
        return {
            data: response.data.map(transformTableItem),
            links: response.links,
        };
    },
    extractCursor: (response) => extractCursor(response.links),
}));
