import { definePlugin } from "../../../utils/plugin-utils";
import { createPaginatedPluginMethod } from "../../../utils/plugin-utils";
import { ListTableRecordsApiResponseSchema, ListTableRecordsOptionsInputSchema, RecordItemSchema, } from "./schemas";
import { tableIdResolver, tableFiltersResolver, tableSortResolver, } from "../../../resolvers";
import { tableRecordFormatter } from "../../../formatters";
import { createFieldKeyTranslator, transformRecordItem, throwOnResponseErrors, } from "../utils";
import { DEFAULT_PAGE_SIZE } from "../../../constants";
import { tablesDefaults } from "../shared";
export const listTableRecordsPlugin = definePlugin((sdk) => createPaginatedPluginMethod(sdk, {
    ...tablesDefaults,
    name: "listTableRecords",
    type: "list",
    itemType: "Record",
    inputSchema: ListTableRecordsOptionsInputSchema,
    outputSchema: RecordItemSchema,
    defaultPageSize: DEFAULT_PAGE_SIZE,
    resolvers: {
        table: tableIdResolver,
        filters: tableFiltersResolver,
        sort: tableSortResolver,
    },
    formatter: tableRecordFormatter,
    handler: async ({ sdk, options, }) => {
        const { api } = sdk.context;
        const tableId = "table" in options ? options.table : options.tableId;
        const translator = await createFieldKeyTranslator({
            api,
            tableId,
            keyMode: options.keyMode,
        });
        const body = {};
        if (options.pageSize !== undefined) {
            body.limit = options.pageSize;
        }
        if (options.filters) {
            body.filters = options.filters.map((f) => ({
                key: translator.translateFieldKey(f.fieldKey),
                operator: f.operator,
                value: f.value,
            }));
        }
        if (options.sort) {
            body.orders = [
                {
                    key: translator.translateFieldKey(options.sort.fieldKey),
                    direction: options.sort.direction,
                },
            ];
        }
        if (options.cursor) {
            body.cursor_query = {
                query_type: "window",
                start_cursor: options.cursor,
            };
        }
        const rawResponse = await api.post(`/tables/api/v1/tables/${tableId}/records/query`, body, {
            searchParams: { allow_nested_queries: "true" },
            authRequired: true,
            resource: { type: "table", id: tableId },
        });
        throwOnResponseErrors(rawResponse);
        const response = ListTableRecordsApiResponseSchema.parse(rawResponse);
        const pagination = response.meta?.pagination;
        const nextCursor = pagination?.has_more && pagination.end_cursor
            ? pagination.end_cursor
            : undefined;
        return {
            data: response.data.map((item) => ({
                ...transformRecordItem(item),
                data: translator.translateOutput(item.data),
            })),
            nextCursor,
        };
    },
}));
