import prisma from "../../config/database"; import { AppError } from "../../utils/AppError"; export class ProjectsService { async getAll(query: { category?: string; search?: string; featured?: string; page?: string; limit?: string }) { const page = parseInt(query.page || "1"); const limit = parseInt(query.limit || "20"); const skip = (page - 1) * limit; const where: any = { published: true }; if (query.category) where.categoryEn = query.category; if (query.featured === "true") where.featured = true; if (query.search) { where.OR = [ { titleEn: { contains: query.search, mode: "insensitive" } }, { titleAr: { contains: query.search, mode: "insensitive" } }, ]; } const [projects, total] = await Promise.all([ prisma.project.findMany({ where, include: { images: true }, orderBy: { sortOrder: "asc" }, skip, take: limit, }), prisma.project.count({ where }), ]); return { projects, total, page, limit }; } async getAllAdmin() { return await prisma.project.findMany({ include: { images: true }, orderBy: { sortOrder: "asc" }, }); } async getById(id: string) { const project = await prisma.project.findUnique({ where: { id }, include: { images: true }, }); if (!project) throw new AppError("Project not found", 404); return project; } async create(data: any) { const { images, ...projectData } = data; return await prisma.project.create({ data: { ...projectData, technologies: Array.isArray(data.technologies) ? data.technologies.join(", ") : data.technologies, images: images ? { create: images.map((url: string) => ({ url })) } : undefined, }, include: { images: true }, }); } async update(id: string, data: any) { const existing = await prisma.project.findUnique({ where: { id } }); if (!existing) throw new AppError("Project not found", 404); const { images, ...projectData } = data; if (images) { await prisma.projectImage.deleteMany({ where: { projectId: id } }); } return await prisma.project.update({ where: { id }, data: { ...projectData, technologies: Array.isArray(data.technologies) ? data.technologies.join(", ") : data.technologies, images: images ? { create: images.map((url: string) => ({ url })) } : undefined, }, include: { images: true }, }); } async delete(id: string) { const existing = await prisma.project.findUnique({ where: { id } }); if (!existing) throw new AppError("Project not found", 404); await prisma.project.delete({ where: { id } }); } async togglePublish(id: string) { const existing = await prisma.project.findUnique({ where: { id } }); if (!existing) throw new AppError("Project not found", 404); return await prisma.project.update({ where: { id }, data: { published: !existing.published }, }); } }