import crypto from "node:crypto"; import { NextResponse } from "next/server"; import type { PageRole } from "@prisma/client"; import { prisma } from "@/lib/db"; import { getCurrentUser } from "@/lib/auth/user"; import { hashPassword, passwordProblem } from "@/lib/auth/password"; import { createSessionToken, COOKIE_NAME, sessionCookieOptions } from "@/lib/auth/session"; import { audit } from "@/lib/audit"; import { readJson, str } from "@/lib/http"; const tokenHash = (token: string) => crypto.createHash("sha256").update(token).digest("hex"); async function validInvite(token: string) { if (!/^[A-Za-z0-9_-]{40,60}$/.test(token)) return null; return prisma.teamInvite.findFirst({ where: { tokenHash: tokenHash(token), status: "PENDING", expiresAt: { gt: new Date() } }, select: { id: true, teamId: true, email: true, pageRoles: true, team: { select: { name: true } } }, }); } export async function GET(_req: Request, ctx: { params: Promise<{ token: string }> }) { const { token } = await ctx.params; const invite = await validInvite(token); if (!invite) return NextResponse.json({ error: "คำเชิญหมดอายุหรือถูกยกเลิก" }, { status: 404 }); const existing = await prisma.user.findUnique({ where: { email: invite.email }, select: { id: true } }); return NextResponse.json({ team: invite.team.name, email: invite.email, existingAccount: Boolean(existing) }); } export async function POST(req: Request, ctx: { params: Promise<{ token: string }> }) { const { token } = await ctx.params; const invite = await validInvite(token); if (!invite) return NextResponse.json({ error: "คำเชิญหมดอายุหรือถูกยกเลิก" }, { status: 404 }); const current = await getCurrentUser(); const existing = await prisma.user.findUnique({ where: { email: invite.email }, select: { id: true, name: true, isActive: true } }); if (existing && (!current || current.id !== existing.id)) return NextResponse.json({ error: "กรุณาเข้าสู่ระบบด้วยอีเมลที่ได้รับคำเชิญก่อน" }, { status: 401 }); if (current && current.email.toLowerCase() !== invite.email) return NextResponse.json({ error: "คำเชิญนี้เป็นของอีเมลอื่น" }, { status: 403 }); if (existing && !existing.isActive) return NextResponse.json({ error: "บัญชีนี้ถูกปิดใช้งาน" }, { status: 403 }); const body = await readJson(req); const name = str(body.name).trim(); const password = str(body.password); if (!existing && (name.length < 2 || name.length > 100 || passwordProblem(password))) { return NextResponse.json({ error: name.length < 2 ? "กรอกชื่ออย่างน้อย 2 ตัวอักษร" : passwordProblem(password) ?? "ชื่อยาวเกินไป" }, { status: 400 }); } const roles = Array.isArray(invite.pageRoles) ? invite.pageRoles as { pageId: string; role: PageRole }[] : []; try { const user = await prisma.$transaction(async (tx) => { const claimed = await tx.teamInvite.updateMany({ where: { id: invite.id, status: "PENDING", expiresAt: { gt: new Date() } }, data: { status: "ACCEPTED", acceptedAt: new Date() } }); if (!claimed.count) throw new Error("Invite already used"); const target = existing ?? await tx.user.create({ data: { email: invite.email, name, passwordHash: await hashPassword(password), globalRole: "MEMBER" }, select: { id: true, name: true, isActive: true } }); await tx.teamMember.upsert({ where: { teamId_userId: { teamId: invite.teamId, userId: target.id } }, create: { teamId: invite.teamId, userId: target.id, role: "MEMBER" }, update: {} }); for (const row of roles) { const attached = await tx.teamPage.findUnique({ where: { pageId: row.pageId }, select: { teamId: true } }); if (attached?.teamId !== invite.teamId) continue; await tx.pageMember.upsert({ where: { userId_pageId: { userId: target.id, pageId: row.pageId } }, create: { userId: target.id, pageId: row.pageId, role: row.role }, update: { role: row.role } }); await audit({ action: "PAGE_MEMBER_SET", actorId: target.id, actorLabel: target.name, pageId: row.pageId, detail: { teamId: invite.teamId, source: "TEAM_INVITE", role: row.role } }, tx); } await audit({ action: "TEAM_INVITE_ACCEPTED", actorId: target.id, actorLabel: target.name, detail: { teamId: invite.teamId, inviteId: invite.id } }, tx); return target; }); const response = NextResponse.json({ ok: true, teamId: invite.teamId }); if (!existing) response.cookies.set(COOKIE_NAME, await createSessionToken({ userId: user.id, email: invite.email, name: user.name, role: "MEMBER", mustChangePassword: false }), sessionCookieOptions(true)); return response; } catch { return NextResponse.json({ error: "รับคำเชิญไม่สำเร็จ กรุณาลองใหม่" }, { status: 409 }); } }