import { UniqueID } from "@repo/rdx-ddd"; import { Result } from "@repo/rdx-utils"; import type { BrandInput } from "../domain/brand.aggregate"; import { Brand, BrandError } from "../domain/brand.aggregate"; import type { IBrandRepository } from "./brand.repository"; import { mapBrandInput } from "./brand-input.mapper"; export class BrandUseCases { constructor(private readonly repository: IBrandRepository) {} list() { return this.repository.list(); } remove(id: string): Promise> { const identity = UniqueID.create(id); if (!identity.isSuccess) { return Promise.resolve(Result.fail(new BrandError("INVALID_REQUEST"))); } return this.repository.remove((brands) => { const brand = brands.find((item) => item.id.equals(identity.data)); if (!brand) { return Result.fail(new BrandError("BRAND_NOT_FOUND")); } if (brand.builtin) { return Result.fail(new BrandError("BUILTIN_PROTECTED")); } return Result.ok(brand); }); } save(id: string | undefined, input: BrandInput): Promise> { if (id && !UniqueID.create(id).isSuccess) { return Promise.resolve(Result.fail(new BrandError("INVALID_REQUEST"))); } return this.repository.save((brands) => { const previous = id ? brands.find((brand) => brand.id.toPrimitive() === id.toLowerCase()) : undefined; if (id && !previous) { return Result.fail(new BrandError("BRAND_NOT_FOUND")); } const mapped = mapBrandInput(input, previous?.builtin ?? false); if (!mapped.isSuccess) { return Result.fail(mapped.error); } if ( brands.some( (brand) => brand !== previous && brand.name .toPrimitive() .localeCompare(mapped.data.name.toPrimitive(), "en", { sensitivity: "base" }) === 0 ) ) { return Result.fail(new BrandError("NAME_EXISTS")); } return previous ? previous.update({ ...mapped.data, logo: input.logoSvg === undefined ? previous.logo : mapped.data.logo, }) : Brand.create(mapped.data); }); } }