import { definePlugin } from "../../../utils/plugin-utils";
import { createPluginMethod } from "../../../utils/plugin-utils";
import { UpdateTableRecordsOptionsInputSchema, UpdateTableRecordsApiResponseSchema, RecordItemSchema, } from "./schemas";
import { tableIdResolver, tableUpdateRecordsResolver, } from "../../../resolvers";
import { tableRecordFormatter } from "../../../formatters";
import { createFieldKeyTranslator, transformRecordItem, throwOnRecordErrors, throwOnResponseErrors, } from "../utils";
import { tablesDefaults } from "../shared";
export const updateTableRecordsPlugin = definePlugin((sdk) => createPluginMethod(sdk, {
    ...tablesDefaults,
    name: "updateTableRecords",
    type: "update",
    itemType: "Record",
    returnType: "RecordItem[]",
    inputSchema: UpdateTableRecordsOptionsInputSchema,
    outputSchema: RecordItemSchema,
    resolvers: {
        table: tableIdResolver,
        records: tableUpdateRecordsResolver,
    },
    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 rawResponse = await api.patch(`/tables/api/v1/tables/${tableId}/records`, {
            updated_records: options.records.map((record) => ({
                id: record.id,
                data: translator.translateInput(record.data),
            })),
        }, { authRequired: true, resource: { type: "table", id: tableId } });
        throwOnResponseErrors(rawResponse);
        const response = UpdateTableRecordsApiResponseSchema.parse(rawResponse);
        for (const changeset of response.data) {
            throwOnRecordErrors(changeset.new);
        }
        return {
            data: response.data.map((changeset) => ({
                ...transformRecordItem(changeset.new),
                data: translator.translateOutput(changeset.new.data),
            })),
        };
    },
}));
