import { definePlugin } from "../../../utils/plugin-utils";
import { createPluginMethod } from "../../../utils/plugin-utils";
import { CreateTableRecordsOptionsInputSchema, CreateTableRecordsApiResponseSchema, RecordItemSchema, } from "./schemas";
import { tableIdResolver, tableRecordsResolver } from "../../../resolvers";
import { tableRecordFormatter } from "../../../formatters";
import { createFieldKeyTranslator, transformRecordItem, throwOnRecordErrors, throwOnResponseErrors, } from "../utils";
import { tablesDefaults } from "../shared";
export const createTableRecordsPlugin = definePlugin((sdk) => createPluginMethod(sdk, {
    ...tablesDefaults,
    name: "createTableRecords",
    type: "create",
    itemType: "Record",
    returnType: "RecordItem[]",
    inputSchema: CreateTableRecordsOptionsInputSchema,
    outputSchema: RecordItemSchema,
    resolvers: { table: tableIdResolver, records: tableRecordsResolver },
    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.post(`/tables/api/v1/tables/${tableId}/records`, {
            new_records: options.records.map((record) => ({
                data: translator.translateInput(record.data),
            })),
        }, { authRequired: true, resource: { type: "table", id: tableId } });
        throwOnResponseErrors(rawResponse);
        const response = CreateTableRecordsApiResponseSchema.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),
            })),
        };
    },
}));
