import bcrypt from 'bcryptjs'; import { Prisma, type GymRole, type PrismaClient } from '@prisma/client'; import { isPrismaNotFound, isPrismaUnique } from '../lib/prisma.js'; import { publicUser } from '../lib/publicUser.js'; import { badRequest, conflict, forbidden, notFound } from '../lib/errors.js'; import { removeGymClaimFiles, removeGymPhotoFiles } from '../lib/uploads.js'; import { gymPhotoUrl, listGymClaimIds } from './gyms.js'; import { resolveMuscleConflicts, toPrismaAvailability, toPrismaJson, type Availability, type SocialMediaEntry, } from './me.js'; export interface CreateGymInput { name: string; location?: string | null; availability?: Availability | null; capacity?: number | null; } export interface UpdateGymInput { name?: string; location?: string | null; availability?: Availability | null; capacity?: number | null; } export interface CreateUserInput { email: string; password: string; firstName?: string; lastName?: string; age?: number; isAdmin?: boolean; } export interface UpdateUserInput { email?: string; firstName?: string | null; lastName?: string | null; nickname?: string | null; socialMedia?: SocialMediaEntry[] | null; age?: number | null; heightCm?: number | null; phone?: string | null; isAdmin?: boolean; password?: string; availability?: Availability | null; priorities?: string | null; exclusions?: string | null; developMuscles?: string[]; canDoMuscles?: string[]; difficultMuscles?: string[]; avoidMuscles?: string[]; } export type MembershipRole = 'OWNER' | 'TRAINER' | 'MEMBER'; /** Upewnia się, że użytkownik istnieje — endpointy admina per-user zwracają 404 zamiast pustych danych. */ export async function ensureUser(prisma: PrismaClient, userId: string) { const user = await prisma.user.findUnique({ where: { id: userId }, select: { id: true } }); if (!user) throw notFound('User not found'); } export async function listGyms(prisma: PrismaClient) { const gyms = await prisma.gym.findMany({ orderBy: { name: 'asc' }, include: { _count: { select: { memberships: true } }, equipment: { include: { equipment: true }, orderBy: { equipment: { name: 'asc' } }, }, photos: { orderBy: [{ order: 'asc' }, { createdAt: 'asc' }], take: 1, }, }, }); return { gyms: gyms.map((g) => { const { photos, ...rest } = g; return { ...rest, coverPhoto: photos[0] ? gymPhotoUrl(g.id, photos[0].id) : null }; }), }; } export async function getGym(prisma: PrismaClient, gymId: string) { const gym = await prisma.gym.findUnique({ where: { id: gymId }, include: { equipment: { include: { equipment: true }, orderBy: { equipment: { name: 'asc' } } }, photos: { orderBy: [{ order: 'asc' }, { createdAt: 'asc' }] }, _count: { select: { memberships: true } }, }, }); if (!gym) throw Object.assign(new Error('Nie znaleziono siłowni'), { status: 404 }); return gym; } export async function createGym(prisma: PrismaClient, data: CreateGymInput) { const { availability, ...rest } = data; const gym = await prisma.gym.create({ data: { ...rest, availability: toPrismaAvailability(availability) }, }); return { gym }; } export async function updateGym(prisma: PrismaClient, id: string, data: UpdateGymInput) { try { const { availability, ...rest } = data; const gym = await prisma.gym.update({ where: { id }, data: { ...rest, availability: toPrismaAvailability(availability) }, }); return { gym }; } catch (e) { if (isPrismaNotFound(e)) throw notFound('Gym not found'); throw e; } } export async function deleteGym(prisma: PrismaClient, id: string) { const claimIds = await listGymClaimIds(prisma, id); try { await prisma.gym.delete({ where: { id } }); } catch (e) { if (isPrismaNotFound(e)) throw notFound('Gym not found'); throw e; } await removeGymClaimFiles(claimIds); removeGymPhotoFiles(id); } /** Add a catalog equipment item to a gym with a quantity (admin, no owner check). */ export async function addGymEquipment( prisma: PrismaClient, gymId: string, equipmentId: string, quantity = 1, ) { const gym = await prisma.gym.findUnique({ where: { id: gymId }, include: { equipment: true }, }); if (!gym) throw notFound('Gym not found'); const item = await prisma.equipment.findUnique({ where: { id: equipmentId } }); if (!item) throw notFound('Equipment not found'); if (gym.equipment.some((e) => e.equipmentId === equipmentId)) throw conflict('Equipment already exists in this gym — update its quantity instead'); try { await prisma.gymEquipment.create({ data: { gymId, equipmentId, quantity } }); } catch (e) { if (isPrismaUnique(e)) throw conflict('Equipment already exists in this gym — update its quantity instead'); throw e; } const updated = await prisma.gym.findUnique({ where: { id: gymId }, include: { equipment: { include: { equipment: true } } }, }); return { gym: updated }; } /** Change the quantity of a gym's equipment item (admin, no owner check). */ export async function updateGymEquipmentQuantity( prisma: PrismaClient, gymId: string, equipmentId: string, quantity: number, ) { const gym = await prisma.gym.findUnique({ where: { id: gymId }, include: { equipment: true }, }); if (!gym) throw notFound('Gym not found'); const link = gym.equipment.find((e) => e.equipmentId === equipmentId); if (!link) throw badRequest('Equipment not found in this gym'); await prisma.gymEquipment.update({ where: { id: link.id }, data: { quantity } }); const updated = await prisma.gym.findUnique({ where: { id: gymId }, include: { equipment: { include: { equipment: true } } }, }); return { gym: updated }; } /** Remove a catalog equipment item from a gym (admin, no owner check). */ export async function removeGymEquipment(prisma: PrismaClient, gymId: string, equipmentId: string) { const gym = await prisma.gym.findUnique({ where: { id: gymId }, include: { equipment: true }, }); if (!gym) throw notFound('Gym not found'); const link = gym.equipment.find((e) => e.equipmentId === equipmentId); if (!link) throw badRequest('Equipment not found in this gym'); await prisma.gymEquipment.delete({ where: { id: link.id } }); const updated = await prisma.gym.findUnique({ where: { id: gymId }, include: { equipment: { include: { equipment: true } } }, }); return { gym: updated }; } /** * Strażnik „ostatniego admina”: nie pozwala odebrać roli (lub usunąć konto) * jedynemu administratorowi — panel straciłby dostęp na stałe (brak UI do * odzyskiwania). Próba samodegradacji/self-deletion wpada w ten sam warunek, * gdy w systemie zostaje zero innych adminów. */ async function assertNotLastAdmin(prisma: PrismaClient, targetId: string, actorId?: string) { const otherAdmins = await prisma.user.count({ where: { isAdmin: true, id: { not: targetId } }, }); if (otherAdmins === 0) { throw forbidden( actorId === targetId ? 'You cannot remove the last admin role from yourself' : 'Cannot remove the last admin role', ); } } export async function listUsers(prisma: PrismaClient, search?: string) { const term = search?.toLowerCase(); const users = await prisma.user.findMany({ where: term ? { OR: [ { email: { contains: term, mode: 'insensitive' } }, { firstName: { contains: term, mode: 'insensitive' } }, { lastName: { contains: term, mode: 'insensitive' } }, ], } : undefined, include: { memberships: { include: { gym: true } } }, orderBy: { createdAt: 'desc' }, }); return { users: users.map((u) => ({ ...publicUser(u), memberships: u.memberships.map((m) => ({ gymId: m.gymId, roles: m.roles, gym: m.gym, })), })), }; } export async function createUser(prisma: PrismaClient, data: CreateUserInput) { const existing = await prisma.user.findUnique({ where: { email: data.email.toLowerCase() }, }); if (existing) throw conflict('Email already registered'); const passwordHash = await bcrypt.hash(data.password, 10); const user = await prisma.user.create({ data: { email: data.email.toLowerCase(), passwordHash, firstName: data.firstName, lastName: data.lastName, age: data.age, isAdmin: data.isAdmin ?? false, }, }); return { user: publicUser(user) }; } export async function updateUser( prisma: PrismaClient, id: string, data: UpdateUserInput, actorId?: string, ) { const user = await prisma.user.findUnique({ where: { id } }); if (!user) throw notFound('User not found'); const email = data.email?.toLowerCase(); if (email && email !== user.email) { const existing = await prisma.user.findUnique({ where: { email } }); if (existing) throw conflict('Email already registered'); } const phone = data.phone; if (phone && phone !== user.phone) { const phoneOwner = await prisma.user.findUnique({ where: { phone } }); if (phoneOwner) throw conflict('Phone already registered'); } const roleChanged = data.isAdmin !== undefined && data.isAdmin !== user.isAdmin; if (roleChanged && data.isAdmin === false) { await assertNotLastAdmin(prisma, id, actorId); } const passwordHash = data.password ? await bcrypt.hash(data.password, 10) : undefined; const muscles = data.developMuscles !== undefined || data.canDoMuscles !== undefined || data.difficultMuscles !== undefined || data.avoidMuscles !== undefined ? resolveMuscleConflicts( { developMuscles: user.developMuscles, canDoMuscles: user.canDoMuscles, difficultMuscles: user.difficultMuscles, avoidMuscles: user.avoidMuscles, }, data, ) : {}; const updated = await prisma.user.update({ where: { id: user.id }, data: { email, firstName: data.firstName, lastName: data.lastName, nickname: data.nickname, socialMedia: toPrismaJson(data.socialMedia), age: data.age, heightCm: data.heightCm, phone: data.phone, isAdmin: data.isAdmin, passwordHash, availability: toPrismaAvailability(data.availability), priorities: data.priorities, exclusions: data.exclusions, ...muscles, ...(roleChanged ? { tokenVersion: { increment: 1 } } : {}), }, }); return { user: publicUser(updated) }; } export async function deleteUser(prisma: PrismaClient, id: string, actorId?: string) { if (actorId && actorId === id) throw forbidden('You cannot delete your own account'); const target = await prisma.user.findUnique({ where: { id }, select: { isAdmin: true } }); if (target?.isAdmin) await assertNotLastAdmin(prisma, id, actorId); try { await prisma.user.delete({ where: { id } }); } catch (e) { if (isPrismaNotFound(e)) throw notFound('User not found'); throw e; } } export async function addMembership( prisma: PrismaClient, userId: string, gymId: string, roles: MembershipRole[], ) { const gym = await prisma.gym.findUnique({ where: { id: gymId } }); if (!gym) throw notFound('Gym not found'); const user = await prisma.user.findUnique({ where: { id: userId } }); if (!user) throw notFound('User not found'); const existing = await prisma.gymMembership.findUnique({ where: { userId_gymId: { userId: user.id, gymId } }, }); if (existing) throw conflict('Membership already exists'); const membership = await prisma.gymMembership.create({ data: { userId: user.id, gymId, roles }, }); return { membership }; } export async function updateMembership( prisma: PrismaClient, userId: string, gymId: string, roles: MembershipRole[], ) { const membership = await prisma.gymMembership.findUnique({ where: { userId_gymId: { userId, gymId } }, }); if (!membership) throw notFound('Membership not found'); const updated = await prisma.gymMembership.update({ where: { userId_gymId: { userId, gymId } }, data: { roles }, }); return { membership: updated }; } export async function removeMembership(prisma: PrismaClient, userId: string, gymId: string) { try { await prisma.gymMembership.delete({ where: { userId_gymId: { userId, gymId } }, }); } catch (e) { if (isPrismaNotFound(e)) throw badRequest('Membership not found'); throw e; } } // ---------- gym claims (admin verification) ---------- export type ClaimStatus = 'PENDING' | 'APPROVED' | 'REJECTED'; /** List gym claims (both types), PENDING first, then createdAt desc. Opcjonalny filtr po statusie i użytkowniku. */ export async function listGymClaims(prisma: PrismaClient, status?: ClaimStatus, userId?: string) { const claims = await prisma.gymClaim.findMany({ where: status || userId ? { ...(status ? { status } : {}), ...(userId ? { userId } : {}) } : undefined, include: { gym: { select: { id: true, name: true, kind: true, isPrivate: true } }, user: { select: { id: true, firstName: true, lastName: true, email: true } }, _count: { select: { documents: true } }, }, }); claims.sort( (a, b) => Number(a.status !== 'PENDING') - Number(b.status !== 'PENDING') || b.createdAt.getTime() - a.createdAt.getTime(), ); return { claims: claims.map((c) => ({ id: c.id, gymId: c.gymId, type: c.gymId ? ('verification' as const) : ('new' as const), gym: c.gym ? { id: c.gym.id, name: c.gym.name, kind: c.gym.kind, isPrivate: c.gym.isPrivate } : null, gymName: c.gymName, gymLocation: c.gymLocation, description: c.description, companyName: c.companyName, nip: c.nip, phone: c.phone, email: c.email, address: c.address, status: c.status, rejectReason: c.rejectReason, createdAt: c.createdAt.toISOString(), user: { id: c.user.id, firstName: c.user.firstName, lastName: c.user.lastName, email: c.user.email, }, documentCount: c._count.documents, })), }; } /** Full claim detail (admin): claim + gym + user + documents. */ export async function getGymClaim(prisma: PrismaClient, claimId: string) { const claim = await prisma.gymClaim.findUnique({ where: { id: claimId }, include: { gym: { select: { id: true, name: true, kind: true, isPrivate: true } }, user: { select: { id: true, firstName: true, lastName: true, email: true, phone: true } }, documents: { select: { id: true, originalName: true, storedName: true, mimeType: true, sizeBytes: true, createdAt: true, }, }, }, }); if (!claim) throw notFound('Claim not found'); return { claim: { id: claim.id, gymId: claim.gymId, type: claim.gymId ? ('verification' as const) : ('new' as const), gym: claim.gym ? { id: claim.gym.id, name: claim.gym.name, kind: claim.gym.kind, isPrivate: claim.gym.isPrivate, } : null, gymName: claim.gymName, gymLocation: claim.gymLocation, gymAvailability: claim.gymAvailability, gymCapacity: claim.gymCapacity, description: claim.description, companyName: claim.companyName, nip: claim.nip, phone: claim.phone, email: claim.email, address: claim.address, status: claim.status, rejectReason: claim.rejectReason, decidedAt: claim.decidedAt ? claim.decidedAt.toISOString() : null, createdAt: claim.createdAt.toISOString(), user: { id: claim.user.id, firstName: claim.user.firstName, lastName: claim.user.lastName, email: claim.user.email, phone: claim.user.phone, }, documents: claim.documents.map((d) => ({ id: d.id, originalName: d.originalName, mimeType: d.mimeType, sizeBytes: d.sizeBytes, createdAt: d.createdAt.toISOString(), })), }, }; } /** * Approve a PENDING claim (transaction): * - verification: gym → REAL + public, applicant → OWNER, other owners → MEMBER, * other pending claims for the gym → REJECTED, address overrides gym.location; * - new real: creates a REAL gym from the claim data, applicant → OWNER, * claim.gymId → the new gym. */ export async function approveGymClaim(prisma: PrismaClient, adminId: string, claimId: string) { await prisma.$transaction(async (tx) => { const claim = await tx.gymClaim.findUnique({ where: { id: claimId } }); if (!claim) throw notFound('Claim not found'); if (claim.status !== 'PENDING') throw conflict('Claim is not pending'); if (claim.gymId) { const gym = await tx.gym.findUnique({ where: { id: claim.gymId } }); if (!gym) throw notFound('Gym not found'); if (gym.kind !== 'VIRTUAL') throw conflict('Only virtual gyms can be verified'); await tx.gym.update({ where: { id: gym.id }, data: { kind: 'REAL', isPrivate: false, ...(claim.address ? { location: claim.address } : {}), }, }); const membership = await tx.gymMembership.findUnique({ where: { userId_gymId: { userId: claim.userId, gymId: gym.id } }, }); if (membership) { const roles: GymRole[] = membership.roles.includes('OWNER') ? membership.roles : ['OWNER', ...membership.roles]; await tx.gymMembership.update({ where: { id: membership.id }, data: { roles } }); } else { await tx.gymMembership.create({ data: { userId: claim.userId, gymId: gym.id, roles: ['OWNER'] }, }); } const otherOwners = await tx.gymMembership.findMany({ where: { gymId: gym.id, userId: { not: claim.userId }, roles: { has: 'OWNER' } }, }); for (const m of otherOwners) { const roles = m.roles.filter((r) => r !== 'OWNER'); await tx.gymMembership.update({ where: { id: m.id }, data: { roles: roles.length > 0 ? roles : ['MEMBER'] }, }); } await tx.gymClaim.updateMany({ where: { gymId: gym.id, status: 'PENDING', id: { not: claim.id } }, data: { status: 'REJECTED', rejectReason: 'Zatwierdzono inny wniosek', decidedById: adminId, decidedAt: new Date(), }, }); } else { const gym = await tx.gym.create({ data: { name: claim.gymName!, location: claim.gymLocation!, availability: claim.gymAvailability === null ? Prisma.DbNull : claim.gymAvailability, capacity: claim.gymCapacity, kind: 'REAL', isPrivate: false, }, }); await tx.gymMembership.create({ data: { userId: claim.userId, gymId: gym.id, roles: ['OWNER'] }, }); await tx.gymClaim.update({ where: { id: claim.id }, data: { gymId: gym.id } }); } await tx.gymClaim.update({ where: { id: claim.id }, data: { status: 'APPROVED', decidedById: adminId, decidedAt: new Date() }, }); }); } /** Reject a PENDING claim with an optional reason. */ export async function rejectGymClaim( prisma: PrismaClient, adminId: string, claimId: string, reason?: string, ) { const claim = await prisma.gymClaim.findUnique({ where: { id: claimId } }); if (!claim) throw notFound('Claim not found'); if (claim.status !== 'PENDING') throw conflict('Claim is not pending'); await prisma.gymClaim.update({ where: { id: claimId }, data: { status: 'REJECTED', rejectReason: reason?.trim() ? reason.trim() : null, decidedById: adminId, decidedAt: new Date(), }, }); }