import { Injectable } from '@nestjs/common'; import { PrismaService } from '../../prisma/prisma.service'; import { Category } from '../../prisma/generated/client'; import { CategoryCreateInput } from '../../prisma/generated/models/Category'; /** Database access to categories. Rows are matched with Hiboutik by `hiboutikId`. */ @Injectable() export class CategoryDatabaseRepository { constructor(private readonly prisma: PrismaService) {} async getAll(): Promise { return this.prisma.category.findMany({ orderBy: { hiboutikId: 'asc' }, }); } /** Creates or updates the category with the same `hiboutikId`. */ async upsert(category: CategoryCreateInput): Promise { return this.prisma.category.upsert({ where: { hiboutikId: category.hiboutikId }, create: category, update: category, }); } /** Links a category to its parent (null for a root category). Both must already exist. */ async setParent(hiboutikId: number, parentHiboutikId: number | null): Promise { return this.prisma.category.update({ where: { hiboutikId }, data: { parent: parentHiboutikId ? { connect: { hiboutikId: parentHiboutikId } } : { disconnect: true } }, }); } /** * Deletes the categories that no longer exist in Hiboutik. * Their products and sub-categories are kept: the relation is set to null (onDelete: SetNull). */ async deleteMissing(keptHiboutikIds: number[]): Promise { const result = await this.prisma.category.deleteMany({ where: { hiboutikId: { notIn: keptHiboutikIds } }, }); return result.count; } }