import { Resource } from "../resource.js";
import { createPrismaApi } from "./api.js";
/**
 * Creates and manages Prisma Postgres projects.
 *
 * Prisma Postgres projects are containers for your databases and
 * their configurations. Projects belong to a workspace and can
 * contain multiple databases.
 *
 * @example
 * // Create a database for a project
 * import { Project, Database } from "alchemy/prisma-postgres";
 * const project = await Project("my-app");
 */
export const Project = Resource("prisma::Project", 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;
    if (this.phase === "delete") {
        if (shouldDelete) {
            await api.deleteProject({
                path: { id: this.output.id },
            });
        }
        return this.destroy();
    }
    if (this.phase === "update") {
        return this.replace();
    }
    const project = await api
        .createProjectWithPostgresDatabase({
        body: {
            createDatabase: false,
            name,
            //! prisma seems to not support setting the workspace on project creation?
        },
    })
        .then((response) => response.data.data);
    return {
        id: project.id,
        name: project.name,
        createdAt: project.createdAt,
        workspace: project.workspace,
    };
});
export async function findProjectByName(props) {
    const api = createPrismaApi(props);
    let hasMore = true;
    let project;
    while (hasMore) {
        const response = await api.listProjects();
        project = response.data.data.find((project) => project.name === props.name);
        if (project != null) {
            break;
        }
        hasMore = response.data.pagination.hasMore;
    }
    return project;
}
//# sourceMappingURL=project.js.map