import { NextRequest, NextResponse } from "next/server";
import { auth } from "@clerk/nextjs/server";
import { getDatabase } from "@/lib/database";
import log from "@/lib/logger";

/**
 * POST /api/notifications/save-token
 * Save the user's Expo push notification token
 */
export async function POST(req: NextRequest) {
  try {
    const { userId } = await auth();

    if (!userId) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const body = await req.json();
    const { expoPushToken, deviceType } = body;

    if (!expoPushToken) {
      return NextResponse.json(
        { error: "Missing required field: expoPushToken" },
        { status: 400 },
      );
    }

    // Validate device type
    if (deviceType && !["ios", "android"].includes(deviceType)) {
      return NextResponse.json(
        { error: "Invalid deviceType. Must be 'ios' or 'android'" },
        { status: 400 },
      );
    }

    const db = await getDatabase();

    // Update user with push token
    const updatedUser = await db.updateUser(userId, {
      expoPushToken,
      deviceType: deviceType || undefined,
    });

    if (!updatedUser) {
      return NextResponse.json({ error: "User not found" }, { status: 404 });
    }

    log.info("Push token saved", {
      userId,
      deviceType,
      tokenPrefix: expoPushToken.substring(0, 20) + "...",
    });

    return NextResponse.json({
      success: true,
      data: {
        message: "Push token saved successfully",
        deviceType: updatedUser.deviceType,
      },
      meta: {
        timestamp: new Date().toISOString(),
      },
    });
  } catch (error) {
    log.error("Failed to save push token", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 },
    );
  }
}
