import assert from "node:assert";
import { extractCloudflareResult } from "../cloudflare/api-response.js";
import { createCloudflareApi, } from "../cloudflare/api.js";
import { memoize } from "../util/memoize.js";
import { importPeer } from "../util/peer.js";
import { MIGRATIONS_DIRECTORY } from "./migrations.js";
import { StateStoreProxy } from "./proxy.js";
/**
 * @deprecated Use `CloudflareStateStore` from `alchemy/state` instead.
 */
export class D1StateStore extends StateStoreProxy {
    options;
    constructor(scope, options = {}) {
        super(scope);
        this.options = options;
    }
    async provision() {
        const db = await createDatabaseClient(this.options);
        const { SQLiteStateStoreOperations } = await import("./operations.js");
        const operations = new SQLiteStateStoreOperations(db, {
            chain: this.scope.chain,
        });
        return operations.dispatch.bind(operations);
    }
}
const createDatabaseClient = memoize(async (options) => {
    const { drizzle } = await importPeer(import("drizzle-orm/sqlite-proxy"), "D1StateStore");
    const api = await createCloudflareApi(options);
    const database = await upsertDatabase(api, options.databaseName ?? "alchemy-state");
    const remoteCallback = async (sql, params) => {
        const [result] = await extractCloudflareResult("execute D1 query", api.post(`/accounts/${api.accountId}/d1/database/${database.id}/raw`, { sql, params }, {
            headers: {
                "Content-Type": "application/json",
            },
        }));
        assert(result, "Missing result");
        return {
            rows: Object.values(result.results.rows),
        };
    };
    return drizzle(remoteCallback, {
        schema: await import("./schema.js"),
    });
});
const upsertDatabase = async (api, databaseName) => {
    const { listDatabases, createDatabase } = await import("../cloudflare/d1-database.js");
    const { listSqlFiles } = await import("../cloudflare/d1-sql-file.js");
    const { applyMigrations } = await import("../cloudflare/d1-migrations.js");
    const migrate = async (databaseId) => {
        await applyMigrations({
            migrationsFiles: await listSqlFiles(MIGRATIONS_DIRECTORY),
            migrationsTable: "migrations",
            accountId: api.accountId,
            databaseId,
            api,
            quiet: true,
        });
    };
    const databases = await listDatabases(api, databaseName);
    if (databases[0]) {
        await migrate(databases[0].uuid);
        return {
            id: databases[0].uuid,
        };
    }
    const database = await createDatabase(api, databaseName, {
        readReplication: { mode: "disabled" },
    });
    await migrate(database.uuid);
    return {
        id: database.uuid,
    };
};
//# sourceMappingURL=d1-state-store.js.map