import type { UniqueID } from "@repo/rdx-ddd"; import type { IResourceRepository, InventoryContext } from "../../application/resource.repository"; import type { IResourceAccessWriter } from "../../application/resource-access-writer"; import { ResourceCatalogError } from "../../domain/resource-definition"; /** Preparación dentro de la transacción de alta; cualquier fallo posterior revierte también el tipo. */ export async function prepareSmbAccess( context: InventoryContext, companyId: UniqueID, creation: Parameters[2], writer: IResourceAccessWriter | undefined ): Promise { if (!creation) { return context; } const template = context.catalog.definitions.find( (item) => item.id.toPrimitive() === creation.templateId.toLowerCase() ); if (template?.stockKey.getOrUndefined() !== "template:shared_folder") { return context; } if (!writer) { throw new ResourceCatalogError("ACCESS_PROJECTION_UNAVAILABLE"); } const prior = context.resources .find( (item) => item.values.toPrimitive().templateId === creation.templateId.toLowerCase() && item.values.toPrimitive().integration?.kind === "access" ) ?.values.toPrimitive().integration; const ensured = await writer.ensureSmbType({ companyId, actorId: creation.actorId, recordedAt: new Date().toISOString(), ...(prior?.kind === "access" ? { preferredTypeId: prior.resourceTypeId } : {}), }); if (!ensured.isSuccess) { throw new ResourceCatalogError("ACCESS_PROJECTION_UNAVAILABLE"); } return { ...context, smbAccessTypeId: ensured.data, references: [ ...context.references, { id: ensured.data, kind: "resource_type", name: "", active: true, systemId: null }, ], }; }