import { NextResponse } from 'next/server' import { getPayload } from 'payload' import configPromise from '@payload-config' import { sendMail } from '@/lib/mail' export const dynamic = 'force-dynamic' const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/ /* POST /api/notify — L-01 launch-notification list. Idempotent: an existing email returns 200 { ok: true, alreadySubscribed: true } (no duplicate row, no re-send). A fresh email is stored and a confirmation is sent; if the mail transport is not wired the response is an honest 503 (the row is kept — no fake success). */ export async function POST(req: Request) { let body: { email?: string } | null = null try { body = await req.json() } catch { return NextResponse.json({ error: 'صيغة الطلب غير صحيحة.' }, { status: 400 }) } const email = (body?.email ?? '').trim().toLowerCase() if (!EMAIL_RE.test(email)) { return NextResponse.json({ error: 'أدخل بريداً إلكترونياً صحيحاً.' }, { status: 400 }) } const payload = await getPayload({ config: configPromise }) const { docs } = await payload.find({ collection: 'launch-notifications', where: { email: { equals: email } }, limit: 1, overrideAccess: true, }) if (docs.length > 0) { return NextResponse.json({ ok: true, alreadySubscribed: true }) } try { await payload.create({ collection: 'launch-notifications', data: { email, source: 'subscription' }, }) } catch (err) { // Lost a unique-constraint race against a concurrent signup → idempotent OK. const message = err instanceof Error ? err.message : '' if (/duplicate key|unique constraint/i.test(message)) { return NextResponse.json({ ok: true, alreadySubscribed: true }) } console.error('launch notification create failed:', err) return NextResponse.json({ error: 'تعذر حفظ البريد، حاول مرة أخرى.' }, { status: 500 }) } const { sent } = await sendMail( email, 'سنعلمك عند تفعيل العضوية — أنور بي آي', 'مرحباً بك في أنور بي آي.\n\nسجّلنا بريدك في قائمة الإشعار، وسنراسلك قبل تفعيل العضوية بأيام.\n\nخلال الوصول المبكر كل الأدلة المنشورة متاحة مجاناً، ولن يُنشأ لك اشتراك أو يُحصَّل أي مبلغ.', ) if (!sent) { return NextResponse.json({ error: 'خدمة البريد غير مربوطة بعد.' }, { status: 503 }) } return NextResponse.json({ ok: true }) }