import type { PrismaClient } from '@prisma/client'; import { badRequest, conflict, forbidden, notFound } from '../../lib/errors.js'; import { formatAddress } from '../../lib/address.js'; import { isPrismaNotFound } from '../../lib/prisma.js'; import { removeGymClaimFiles, removeGymPhotoFiles } from '../../lib/uploads.js'; import { toPrismaAvailability, type Availability } from '../me.js'; import { gymCoverInclude, gymEquipmentInclude } from './includes.js'; import { coverUrlOf } from './photos.js'; export type GymKind = 'VIRTUAL' | 'REAL'; export interface CreateGymInput { name: string; location?: string | null; /** Adres strukturalny — wymagany dla REAL; `location` jest z niego derivowany. */ addressLine1?: string | null; addressLine2?: string | null; postalCode?: string | null; city?: string | null; countryCode?: string | null; availability?: Availability | null; capacity?: number | null; kind?: GymKind; isPrivate?: boolean; } export interface UpdateGymInput { name?: string; location?: string | null; addressLine1?: string | null; addressLine2?: string | null; postalCode?: string | null; city?: string | null; countryCode?: string | null; availability?: Availability | null; capacity?: number | null; isPrivate?: boolean; } export async function listUserGyms(prisma: PrismaClient, userId: string) { const memberships = await prisma.gymMembership.findMany({ where: { userId }, include: { gym: { include: { ...gymEquipmentInclude, ...gymCoverInclude } } }, orderBy: { gym: { name: 'asc' } }, }); return { gyms: memberships.map((m) => { const { photos, ...gym } = m.gym; return { ...gym, coverPhoto: coverUrlOf(gym.id, photos), roles: m.roles }; }), }; } /** All REAL gyms in the system (for selecting an existing gym). */ export async function listAllGyms(prisma: PrismaClient) { const gyms = await prisma.gym.findMany({ where: { kind: 'REAL' }, include: { ...gymEquipmentInclude, ...gymCoverInclude }, orderBy: { name: 'asc' }, }); return { gyms: gyms.map((g) => { const { photos, ...rest } = g; return { ...rest, coverPhoto: coverUrlOf(g.id, photos) }; }), }; } /** * Public virtual gyms (with rating counts, the caller's vote and claim status) * plus the caller's own private virtual gyms (no rating fields). * Public: score (up-down) desc, then name asc; own private last, by name. */ export async function listVirtualGyms(prisma: PrismaClient, userId: string) { const [publicGyms, privateGyms, claims, myRatings] = await Promise.all([ prisma.gym.findMany({ where: { kind: 'VIRTUAL', isPrivate: false }, include: { ...gymEquipmentInclude, ratings: true, _count: { select: { memberships: true } } }, }), prisma.gym.findMany({ where: { kind: 'VIRTUAL', isPrivate: true, memberships: { some: { userId, roles: { has: 'OWNER' } } }, }, include: { ...gymEquipmentInclude, _count: { select: { memberships: true } } }, }), prisma.gymClaim.findMany({ where: { userId, status: { in: ['PENDING', 'REJECTED'] } }, select: { gymId: true, status: true, rejectReason: true }, orderBy: { createdAt: 'desc' }, }), prisma.gymRating.findMany({ where: { userId }, select: { gymId: true, vote: true }, }), ]); const myVoteByGym = new Map(myRatings.map((r) => [r.gymId, r.vote])); const claimByGym = new Map(); for (const c of claims) { if (c.gymId && !claimByGym.has(c.gymId)) claimByGym.set(c.gymId, c); } const publicList = publicGyms.map((g) => { const up = g.ratings.filter((r) => r.vote === 'UP').length; const down = g.ratings.filter((r) => r.vote === 'DOWN').length; const claim = claimByGym.get(g.id); return { id: g.id, name: g.name, location: g.location, availability: g.availability, capacity: g.capacity, kind: g.kind, isPrivate: g.isPrivate, equipment: g.equipment, memberCount: g._count.memberships, up, down, myVote: myVoteByGym.get(g.id) ?? null, claimStatus: claim?.status ?? null, rejectReason: claim?.status === 'REJECTED' ? claim.rejectReason ?? null : null, }; }); publicList.sort( (a, b) => b.up - b.down - (a.up - a.down) || a.name.localeCompare(b.name, 'pl'), ); const privateList = privateGyms .map((g) => ({ ...g, isPrivate: true, memberCount: g._count.memberships })) .sort((a, b) => a.name.localeCompare(b.name, 'pl')); return { gyms: [...publicList, ...privateList] }; } /** * Thumb vote on a public virtual gym (how well it mirrors the real one). * Upsert with toggle: the same vote again removes it. The owner cannot vote. */ export async function rateGym( prisma: PrismaClient, userId: string, gymId: string, vote: 'UP' | 'DOWN', ) { const gym = await prisma.gym.findUnique({ where: { id: gymId } }); if (!gym) throw notFound('Gym not found'); if (gym.kind !== 'VIRTUAL' || gym.isPrivate) throw conflict('Only public virtual gyms can be rated'); const isOwner = await prisma.gymMembership.findFirst({ where: { gymId, userId, roles: { has: 'OWNER' } }, }); if (isOwner) throw forbidden('The gym owner cannot rate their own gym'); const existing = await prisma.gymRating.findUnique({ where: { gymId_userId: { gymId, userId } }, }); if (existing?.vote === vote) { await prisma.gymRating.delete({ where: { id: existing.id } }); } else { await prisma.gymRating.upsert({ where: { gymId_userId: { gymId, userId } }, update: { vote }, create: { gymId, userId, vote }, }); } const [up, down] = await Promise.all([ prisma.gymRating.count({ where: { gymId, vote: 'UP' } }), prisma.gymRating.count({ where: { gymId, vote: 'DOWN' } }), ]); return { vote: existing?.vote === vote ? null : vote, up, down }; } /** Join an existing gym (creates a MEMBER membership). Private gyms are invitation-only. */ export async function joinGym(prisma: PrismaClient, userId: string, gymId: string) { const gym = await prisma.gym.findUnique({ where: { id: gymId } }); if (!gym) throw notFound('Gym not found'); if (gym.isPrivate) throw forbidden('Private gyms are invitation-only'); const existing = await prisma.gymMembership.findUnique({ where: { userId_gymId: { userId, gymId } }, }); if (existing) throw conflict('Already a member of this gym'); const membership = await prisma.gymMembership.create({ data: { userId, gymId, roles: ['MEMBER'] }, }); return { membership: { gymId, name: gym.name, roles: membership.roles } }; } /** * Create a gym; the creator becomes its OWNER. * Non-admins can only create VIRTUAL gyms (location required); passing REAL → 403. * Admins pick the kind (default VIRTUAL); isPrivate is only allowed for VIRTUAL. */ export async function createGym( prisma: PrismaClient, userId: string, data: CreateGymInput, isAdmin: boolean, ) { let kind: GymKind = data.kind ?? 'VIRTUAL'; if (!isAdmin) { if (kind === 'REAL') throw forbidden('Only admins can create real gyms'); kind = 'VIRTUAL'; } if (kind === 'VIRTUAL' && !data.location?.trim()) throw badRequest('Location is required for virtual gyms'); const isPrivate = data.isPrivate ?? false; if (kind === 'REAL' && isPrivate) throw badRequest('Real gyms are always public'); // REAL: adres strukturalny wymagany, display string `location` liczony z adresu (jak w panelu admina). const hasAddress = !!(data.addressLine1?.trim() && data.postalCode?.trim() && data.city?.trim()); if (kind === 'REAL' && !hasAddress) throw badRequest('Address (street, postal code, city) is required for real gyms'); const location = kind === 'REAL' ? formatAddress(data) : data.location ?? null; const address = kind === 'REAL' ? { addressLine1: data.addressLine1!.trim(), addressLine2: data.addressLine2?.trim() || null, postalCode: data.postalCode!.trim(), city: data.city!.trim(), countryCode: (data.countryCode ?? 'PL').toUpperCase(), } : {}; const gym = await prisma.gym.create({ data: { name: data.name, location, ...address, availability: toPrismaAvailability(data.availability ?? null), capacity: data.capacity ?? null, kind, isPrivate, }, }); await prisma.gymMembership.create({ data: { userId, gymId: gym.id, roles: ['OWNER'] }, }); return { gym: { ...gym, roles: ['OWNER'] } }; } export async function assertGymOwner(prisma: PrismaClient, gymId: string, userId: string) { const gym = await prisma.gym.findUnique({ where: { id: gymId }, include: { memberships: { where: { userId } }, equipment: true }, }); if (!gym) throw notFound('Gym not found'); const isOwner = gym.memberships.some((m) => m.roles.includes('OWNER')); if (!isOwner) throw forbidden('Only the gym owner can manage this gym'); return gym; } /** Update a gym's data (owner only). isPrivate is only allowed for VIRTUAL gyms. */ export async function updateOwnedGym( prisma: PrismaClient, gymId: string, userId: string, data: UpdateGymInput, ) { const gym = await assertGymOwner(prisma, gymId, userId); if (data.isPrivate === true && gym.kind === 'REAL') throw badRequest('Real gyms are always public'); try { const { availability, addressLine1, addressLine2, postalCode, city, countryCode, ...rest } = data; // Zmiana dowolnego pola adresu → scalenie ze stanem w bazie i przeliczenie `location`. let addressData: Record = {}; const hasAddress = [addressLine1, addressLine2, postalCode, city, countryCode].some( (v) => v !== undefined, ); if (hasAddress) { const merged = { addressLine1: addressLine1 !== undefined ? addressLine1 : gym.addressLine1, addressLine2: addressLine2 !== undefined ? addressLine2 : gym.addressLine2, postalCode: postalCode !== undefined ? postalCode : gym.postalCode, city: city !== undefined ? city : gym.city, countryCode: countryCode !== undefined ? countryCode ? countryCode.trim().toUpperCase() : null : gym.countryCode, }; addressData = { ...merged, location: formatAddress(merged) }; } const updated = await prisma.gym.update({ where: { id: gymId }, data: { ...rest, ...addressData, availability: toPrismaAvailability(availability) }, }); return { gym: updated }; } catch (e) { if (isPrismaNotFound(e)) throw notFound('Gym not found'); throw e; } } /** Delete a gym (owner only). Memberships are removed; user plans are kept. */ export async function deleteOwnedGym(prisma: PrismaClient, gymId: string, userId: string) { const gym = await assertGymOwner(prisma, gymId, userId); const claimIds = await listGymClaimIds(prisma, gymId); try { await prisma.gym.delete({ where: { id: gymId } }); } catch (e) { if (isPrismaNotFound(e)) throw notFound('Gym not found'); throw e; } await removeGymClaimFiles(claimIds); removeGymPhotoFiles(gymId); return { name: gym.name }; } export async function listGymClaimIds(prisma: PrismaClient, gymId: string): Promise { const claims = await prisma.gymClaim.findMany({ where: { gymId }, select: { id: true }, }); return claims.map((c) => c.id); }