import { NextRequest, NextResponse } from "next/server";
import { getDatabase } from "../../../../lib/database/index";
import log from "@/lib/logger";

export async function POST(request: NextRequest) {
  try {
    const db = await getDatabase();
    const profileData = await request.json();

    if (
      !profileData.userId ||
      !profileData.height ||
      !profileData.weight ||
      !profileData.age
    ) {
      return NextResponse.json(
        { error: "Missing required fields" },
        { status: 400 },
      );
    }

    // Check if user exists
    const user = await db.getUserById(profileData.userId);
    if (!user) {
      return NextResponse.json({ error: "User not found" }, { status: 404 });
    }

    // Check if profile already exists
    const existingProfile = await db.getFitnessProfileByUserId(
      profileData.userId,
    );

    let profile;
    if (existingProfile) {
      profile = await db.updateFitnessProfile(profileData.userId, profileData);
    } else {
      profile = await db.createFitnessProfile(profileData);
    }

    return NextResponse.json(
      {
        message: "Fitness profile saved successfully",
        profile,
      },
      { status: 201 },
    );
  } catch (error) {
    log.error("Failed to save fitness profile", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 },
    );
  }
}

export async function GET(request: NextRequest) {
  try {
    const db = await getDatabase();
    const { searchParams } = new URL(request.url);
    const userId = searchParams.get("userId");

    if (userId) {
      const profile = await db.getFitnessProfileByUserId(userId);
      if (!profile) {
        return NextResponse.json(
          { error: "Profile not found" },
          { status: 404 },
        );
      }
      return NextResponse.json({ profile });
    }

    const profiles = await db.getAllFitnessProfiles();
    return NextResponse.json({ profiles });
  } catch (error) {
    log.error("Failed to get fitness profiles", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 },
    );
  }
}
