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

// Helper to add CORS headers
function corsHeaders() {
  return {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
    "Access-Control-Allow-Headers": "Content-Type, Authorization",
  };
}

// Helper to get user ID from auth (works with both web sessions and mobile tokens)
async function getAuthenticatedUserId(
  req: NextRequest,
): Promise<string | null> {
  // The auth() function from Clerk should handle Bearer tokens automatically
  // when called within an API route that's processed by clerkMiddleware
  const { userId } = await auth();
  return userId;
}

// OPTIONS - Handle preflight requests
export async function OPTIONS() {
  return NextResponse.json({}, { headers: corsHeaders() });
}

// GET - List user's fitness goals
export async function GET(req: NextRequest) {
  try {
    const userId = await getAuthenticatedUserId(req);

    if (!userId) {
      log.error("Fitness goals GET - authentication failed", undefined, {
        headers: Object.fromEntries(req.headers.entries()),
      });
      return NextResponse.json(
        { error: "Unauthorized" },
        { status: 401, headers: corsHeaders() },
      );
    }

    log.debug("Fitness goals GET - authenticated user", { userId });

    const { searchParams } = new URL(req.url);
    const targetUserId = searchParams.get("userId") || userId;
    const status = searchParams.get("status"); // active, completed, all

    const db = await getDatabase();

    // Fetch goals with optional status filter
    const goals = await db.getFitnessGoalsByUserId(
      targetUserId,
      status && status !== "all" ? status : undefined,
    );

    log.debug("Fitness goals retrieved", {
      count: goals.length,
      userId: targetUserId,
    });
    return NextResponse.json(goals, { headers: corsHeaders() });
  } catch (error) {
    log.error("Failed to get fitness goals", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500, headers: corsHeaders() },
    );
  }
}

// POST - Create new fitness goal
export async function POST(req: NextRequest) {
  try {
    const userId = await getAuthenticatedUserId(req);

    if (!userId) {
      log.error("Fitness goals POST - authentication failed");
      return NextResponse.json(
        { error: "Unauthorized" },
        { status: 401, headers: corsHeaders() },
      );
    }

    const body = await req.json();
    const {
      goalType,
      title,
      description,
      targetValue,
      currentValue,
      unit,
      targetDate,
      priority,
      notes,
      fitnessProfileId,
    } = body;

    // Validation
    if (!goalType || !title) {
      return NextResponse.json(
        { error: "goalType and title are required" },
        { status: 400, headers: corsHeaders() },
      );
    }

    const db = await getDatabase();

    // Create the goal
    const goal = await db.createFitnessGoal({
      id: randomBytes(16).toString("hex"),
      userId,
      fitnessProfileId: fitnessProfileId || undefined,
      goalType,
      title,
      description: description || undefined,
      targetValue: targetValue || undefined,
      currentValue: currentValue || 0,
      unit: unit || undefined,
      startDate: new Date(),
      targetDate: targetDate ? new Date(targetDate) : undefined,
      status: "active",
      progress: 0,
      priority: priority || "medium",
      notes: notes || undefined,
    });

    log.info("Fitness goal created", { goalId: goal.id, userId });
    return NextResponse.json(goal, { status: 201, headers: corsHeaders() });
  } catch (error) {
    log.error("Failed to create fitness goal", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500, headers: corsHeaders() },
    );
  }
}
