import crypto from "node:crypto"; import { NextResponse } from "next/server"; import type { PageRole } from "@prisma/client"; import { appUrl } from "@/lib/base-path"; import { prisma } from "@/lib/db"; import { actorLabel, pageRoleOf } from "@/lib/auth/user"; import { PAGE_ROLES, roleAtLeast } from "@/lib/auth/roles"; import { requireTeamManager } from "@/lib/teams/access"; import { audit } from "@/lib/audit"; import { readJson, str } from "@/lib/http"; export async function POST(req: Request, ctx: { params: Promise<{ id: string }> }) { const { id } = await ctx.params; const auth = await requireTeamManager(id); if (!auth.ok) return auth.response; const body = await readJson(req); const email = str(body.email).trim().toLowerCase(); if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) return NextResponse.json({ error: "กรอกอีเมลให้ถูกต้อง" }, { status: 400 }); if (email === auth.user.email.toLowerCase()) return NextResponse.json({ error: "คุณอยู่ในทีมนี้แล้ว" }, { status: 400 }); const existingUser = await prisma.user.findUnique({ where: { email }, select: { id: true } }); if (existingUser && await prisma.teamMember.findUnique({ where: { teamId_userId: { teamId: id, userId: existingUser.id } } })) { return NextResponse.json({ error: "ผู้ใช้นี้อยู่ในทีมแล้ว" }, { status: 409 }); } const rawRoles = Array.isArray(body.pageRoles) ? body.pageRoles : []; const pageRoles: { pageId: string; role: PageRole }[] = []; for (const row of rawRoles) { const pageId = str(row?.pageId); const role = str(row?.role) as PageRole; if (!pageId || !PAGE_ROLES.includes(role) || pageRoles.some((x) => x.pageId === pageId)) return NextResponse.json({ error: "สิทธิ์เพจไม่ถูกต้อง" }, { status: 400 }); const teamPage = await prisma.teamPage.findUnique({ where: { pageId }, select: { teamId: true } }); const inviterRole = await pageRoleOf(auth.user, pageId); if (teamPage?.teamId !== id || !roleAtLeast(inviterRole, "MANAGER")) return NextResponse.json({ error: "คุณไม่มีสิทธิ์ให้คนอื่นเข้าถึงเพจนี้" }, { status: 403 }); pageRoles.push({ pageId, role }); } const token = crypto.randomBytes(32).toString("base64url"); const tokenHash = crypto.createHash("sha256").update(token).digest("hex"); const invite = await prisma.$transaction(async (tx) => { await tx.teamInvite.updateMany({ where: { teamId: id, email, status: "PENDING" }, data: { status: "REVOKED" } }); const created = await tx.teamInvite.create({ data: { teamId: id, email, tokenHash, invitedById: auth.user.id, pageRoles, expiresAt: new Date(Date.now() + 7 * 86400000) } }); await audit({ action: "TEAM_INVITE_CREATED", actorId: auth.user.id, actorLabel: actorLabel(auth.user), detail: { teamId: id, inviteId: created.id, email, pageRoles } }, tx); return created; }); return NextResponse.json({ invite: { id: invite.id, email, expiresAt: invite.expiresAt }, url: `${appUrl(new URL(req.url).origin)}/join/${token}` }, { status: 201 }); } export async function DELETE(req: Request, ctx: { params: Promise<{ id: string }> }) { const { id } = await ctx.params; const auth = await requireTeamManager(id); if (!auth.ok) return auth.response; const inviteId = new URL(req.url).searchParams.get("inviteId") ?? ""; const changed = await prisma.teamInvite.updateMany({ where: { id: inviteId, teamId: id, status: "PENDING" }, data: { status: "REVOKED" } }); if (!changed.count) return NextResponse.json({ error: "ไม่พบคำเชิญ" }, { status: 404 }); await audit({ action: "TEAM_INVITE_REVOKED", actorId: auth.user.id, actorLabel: actorLabel(auth.user), detail: { teamId: id, inviteId } }); return NextResponse.json({ ok: true }); }