import { Resource } from "../resource.js";
import { createPrismaApi } from "./api.js";
/**
 * Creates and manages Prisma Postgres databases.
 *
 * Prisma Postgres databases are fully managed PostgreSQL instances
 * that can be connected to applications. Databases belong to a
 * Prisma Postgres project.
 *
 * @example
 * // Create a database for a project
 * import { Project, Database } from "alchemy/prisma-postgres";
 * const project = await Project("my-app");
 * const database = await Database("my-database", {
 *   project: project,
 * });
 *
 * @example
 * // Create a database in the asia pacific region
 * import { Project, Database } from "alchemy/prisma-postgres";
 * const project = await Project("my-app");
 * const database = await Database("my-database", {
 *   project: project,
 *   region: "ap-northeast-1",
 * });
 *
 * @example
 * // Create a database and fully delete on destroy
 * import { Project, Database } from "alchemy/prisma-postgres";
 * const project = await Project("my-app");
 * const database = await Database("my-database", {
 *   project: project,
 *   delete: true,
 * });
 */
export const Database = Resource("prisma::Database", async function (id, props) {
    const api = createPrismaApi({
        serviceToken: props.serviceToken,
    });
    const name = props.name ?? this.output?.name ?? this.scope.createPhysicalName(id);
    const shouldDelete = props.delete ?? false;
    const project = typeof props.project === "string" ? props.project : props.project.id;
    if (this.phase === "delete") {
        if (shouldDelete) {
            await api.deleteDatabase({
                path: { databaseId: this.output.id },
            });
        }
        return this.destroy();
    }
    if (this.phase === "update") {
        return this.replace();
    }
    const database = await api
        .createDatabase({
        path: {
            projectId: project,
        },
        body: {
            isDefault: false,
            name,
            region: props.region,
        },
    })
        .then((response) => response.data.data);
    return {
        id: database.id,
        name: database.name,
        region: database.region?.id,
        status: database.status,
        createdAt: database.createdAt,
        project,
    };
});
export async function findDatabaseByName(props) {
    const api = createPrismaApi({
        serviceToken: props.serviceToken,
    });
    const project = typeof props.project === "string" ? props.project : props.project.id;
    const databases = await api.listDatabases({
        path: {
            projectId: project,
        },
    });
    const database = databases.data.data.find((db) => db.name === props.name);
    return database;
}
//# sourceMappingURL=database.js.map