import prisma from '../config/database'; import { Prisma, UserRole, UserStatus } from '@prisma/client'; export class UserRepository { async create(data: Prisma.UserCreateInput) { return prisma.user.create({ data }); } async findById(id: string) { return prisma.user.findUnique({ where: { id } }); } async findByEmail(email: string) { return prisma.user.findUnique({ where: { email } }); } async findByEmailVerifyToken(token: string) { return prisma.user.findFirst({ where: { emailVerifyToken: token } }); } async update(id: string, data: Prisma.UserUpdateInput) { return prisma.user.update({ where: { id }, data }); } async updateRole(id: string, role: UserRole) { return prisma.user.update({ where: { id }, data: { role } }); } async suspend(id: string) { return prisma.user.update({ where: { id }, data: { status: UserStatus.SUSPENDED }, }); } async activate(id: string) { return prisma.user.update({ where: { id }, data: { status: UserStatus.ACTIVE }, }); } async findAll(page: number, limit: number, search?: string) { const where: Prisma.UserWhereInput = search ? { OR: [ { email: { contains: search } }, { name: { contains: search } }, ], } : {}; const [users, total] = await Promise.all([ prisma.user.findMany({ where, skip: (page - 1) * limit, take: limit, orderBy: { createdAt: 'desc' }, select: { id: true, email: true, name: true, role: true, status: true, isEmailVerified: true, lastLoginAt: true, createdAt: true, }, }), prisma.user.count({ where }), ]); return { users, total, page, limit, totalPages: Math.ceil(total / limit) }; } async countByRole() { const counts = await prisma.user.groupBy({ by: ['role'], _count: true, }); return counts; } async getTotalCount() { return prisma.user.count(); } } export default new UserRepository();