Files

85 lines
2.4 KiB
TypeScript

import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { requireAdmin } from "@/lib/session";
import bcrypt from "bcryptjs";
export async function PATCH(
req: NextRequest,
{ params }: { params: { id: string } }
) {
const admin = await requireAdmin();
if (!admin) return NextResponse.json({ error: "Admin requis" }, { status: 403 });
const body = await req.json().catch(() => ({}));
const id = params?.id || body.id;
if (!id) return NextResponse.json({ error: "id requis" }, { status: 400 });
const { id: _bodyId, ...data } = body;
const allowed = [
"name", "email", "isMuayThai", "isYoga", "role", "phone", "avatar", "password"
];
const updateData: any = {};
for (const key of allowed) {
if (data[key] !== undefined) updateData[key] = data[key];
}
if (updateData.email) updateData.email = updateData.email.toLowerCase();
if (updateData.password) {
if (updateData.password.length < 6) {
return NextResponse.json(
{ error: "Le mot de passe doit contenir au moins 6 caractères" },
{ status: 400 }
);
}
updateData.password = await bcrypt.hash(updateData.password, 10);
}
try {
if (updateData.isMuayThai === true) {
await prisma.muayThaiProfile.upsert({
where: { userId: id },
update: {},
create: { userId: id },
});
}
if (updateData.isYoga === true) {
await prisma.yogaProfile.upsert({
where: { userId: id },
update: {},
create: { userId: id },
});
}
const user = await prisma.user.update({
where: { id },
data: updateData,
});
const { password: _, ...safeUser } = user;
return NextResponse.json(safeUser);
} catch (error) {
console.error(error);
return NextResponse.json({ error: "Erreur" }, { status: 500 });
}
}
export async function DELETE(
req: NextRequest,
{ params }: { params: { id: string } }
) {
const admin = await requireAdmin();
if (!admin) return NextResponse.json({ error: "Admin requis" }, { status: 403 });
const body = await req.json().catch(() => ({}));
const id = params?.id || body.id;
if (!id) return NextResponse.json({ error: "id requis" }, { status: 400 });
try {
await prisma.user.delete({ where: { id } });
return NextResponse.json({ ok: true });
} catch {
return NextResponse.json({ error: "Erreur" }, { status: 500 });
}
}