import type { UniqueID } from "@repo/rdx-ddd"; import type { ResourceDefinitionSpec } from "../domain/resource-definition"; import type { IResourceRepository } from "./resource.repository"; export interface IResourceInventoryService { list(company: UniqueID): Promise< readonly { id: UniqueID; name: string; active: boolean; usage: "application" | "certificate" | "support" | null; expiresOn: string | null; }[] >; } export class ResourceInventoryService implements IResourceInventoryService { constructor(private readonly repository: IResourceRepository) {} async list(company: UniqueID) { const result = await this.repository.get(company); if (!result.isSuccess) { throw new Error("No se pudo consultar el inventario de recursos."); } const expiryFieldId = result.data.catalog.definitions .find((item) => item.stockKey.getOrUndefined() === "field:expires") ?.id.toPrimitive(); return result.data.resources.map((resource) => { const template = result.data.catalog.definitions.find( (item) => item.id.toPrimitive() === resource.values.toPrimitive().templateId ); const data = template?.values.data; const key = template?.stockKey.getOrUndefined(); const usage = resourceUsage(key, data); const expiresOn = expiryFieldId ? resource.values.toPrimitive().characteristics[expiryFieldId] : null; return { id: resource.id, name: resource.values.toPrimitive().name, active: resource.values.toPrimitive().active, usage, expiresOn: typeof expiresOn === "string" ? expiresOn : null, }; }); } } function resourceUsage(key: string | undefined, definition: ResourceDefinitionSpec | undefined) { switch (key) { case "template:application": return "application"; case "template:certificate": return "certificate"; case "template:support": return "support"; default: return definition?.kind === "template" ? (definition.usage ?? null) : null; } }