import { UniqueID } from "@repo/rdx-ddd"; import { Maybe, Result } from "@repo/rdx-utils"; import type { AssetDefinitionSpec } from "../../common"; import { AssetCatalogError } from "../domain/asset-definition"; import { AssetDefinitionValues } from "../domain/value-objects/asset-definition-values"; import type { IAssetCatalogRepository } from "./asset-catalog.repository"; export function catalogScope(value: string) { if (value === "global") { return Result.ok(Maybe.none()); } const id = UniqueID.create(value); return id.isSuccess ? Result.ok(Maybe.some(id.data)) : Result.fail(new AssetCatalogError("INVALID_REQUEST")); } export class AssetCatalogUseCases { constructor(private readonly repository: IAssetCatalogRepository) {} async get(scope: string) { const parsed = catalogScope(scope); return parsed.isSuccess ? this.repository.get(parsed.data) : parsed; } async save(scope: string, identity: string | undefined, input: AssetDefinitionSpec) { const parent = catalogScope(scope); const values = AssetDefinitionValues.create(input); const id = identity ? UniqueID.create(identity) : Result.ok(undefined); if (!parent.isSuccess) { return parent; } if (!values.isSuccess) { return values; } if (!id.isSuccess) { return Result.fail(new AssetCatalogError("INVALID_REQUEST")); } return this.repository.update(parent.data, (catalog) => catalog.save(parent.data, id.data ? Maybe.some(id.data) : Maybe.none(), values.data) ); } async setActive(scope: string, identity: string, active: boolean | null) { const parent = catalogScope(scope); const id = UniqueID.create(identity); if (!parent.isSuccess) { return parent; } if (!id.isSuccess) { return Result.fail(new AssetCatalogError("INVALID_REQUEST")); } return this.repository.update(parent.data, (catalog) => catalog.setActive(parent.data, id.data, active) ); } }