import { definePlugin } from "../../../utils/plugin-utils";
import { createPluginMethod } from "../../../utils/plugin-utils";
import { ListTableFieldsOptionsInputSchema, ListTableFieldsApiResponseSchema, FieldItemSchema, } from "./schemas";
import { tableIdResolver } from "../../../resolvers";
import { resolveFieldKeys, transformFieldItem } from "../utils";
import { tablesDefaults } from "../shared";
export const listTableFieldsPlugin = definePlugin((sdk) => createPluginMethod(sdk, {
    ...tablesDefaults,
    name: "listTableFields",
    type: "list",
    itemType: "Field",
    inputSchema: ListTableFieldsOptionsInputSchema,
    outputSchema: FieldItemSchema,
    resolvers: { table: tableIdResolver },
    handler: async ({ sdk, options }) => {
        const { api } = sdk.context;
        const tableId = "table" in options ? options.table : options.tableId;
        const fieldKeys = "fields" in options ? options.fields : options.fieldKeys;
        const searchParams = {};
        if (fieldKeys && fieldKeys.length > 0) {
            const numericIds = await resolveFieldKeys({
                api,
                tableId,
                fieldKeys,
            });
            searchParams.field_ids = numericIds.join(",");
        }
        const rawResponse = await api.get(`/tables/api/v1/tables/${tableId}/fields`, {
            searchParams: Object.keys(searchParams).length > 0 ? searchParams : undefined,
            authRequired: true,
            resource: { type: "table", id: tableId },
        });
        const response = ListTableFieldsApiResponseSchema.parse(rawResponse);
        return { data: response.data.map(transformFieldItem) };
    },
}));
