import { NextRequest, NextResponse } from "next/server";
import { getDatabase } from "../../../../lib/database/index";
import log from "@/lib/logger";
import { fitnessProfileSchema } from "@/lib/validation/schemas";
import {
  validateRequestBody,
  validationErrorResponse,
} from "@/lib/validation/helpers";

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

    // Validate request body
    const validation = await validateRequestBody(request, fitnessProfileSchema);

    if (!validation.success) {
      log.warn("Fitness profile validation failed", {
        errors: validation.errors,
      });
      return validationErrorResponse(validation.errors);
    }

    const profileData = validation.data;

    // 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) {
      // Update - omit userId from update data
      const { userId, ...updateData } = profileData;
      profile = await db.updateFitnessProfile(userId, updateData as any);
    } else {
      // Create - omit userId since the function signature expects it separately
      const { userId, ...createData } = profileData;
      profile = await db.createFitnessProfile({ userId, ...createData } as any);
    }

    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 },
    );
  }
}
