/**
 * POST /api/sms/request-optin — start SMS opt-in verification.
 */
import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { requestSmsOptIn } from "@/lib/services/sms-sender";

export const dynamic = "force-dynamic";

const E164_RE = /^\+[1-9]\d{1,14}$/;

export async function POST(req: Request) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  const body = await req.json().catch(() => null) as { phone?: string } | null;
  if (!body?.phone || !E164_RE.test(body.phone)) return NextResponse.json({ error: "Valid E.164 phone number required (e.g., +15551234567)" }, { status: 400 });

  await requestSmsOptIn(user.id, body.phone);
  return NextResponse.json({ success: true });
}
