fitness profile

functionality added, need polishing
This commit is contained in:
dimitar committed 2025-11-11 02:16:29 +01:00
1 parent 64bc4aa58b
commit b9f33fdcc6
13 files changed
+1590 -7

No files matched your search

@@ -0,0 +1,135 @@
import { NextRequest, NextResponse } from "next/server";
import { auth } from "@clerk/nextjs/server";
import Database from "better-sqlite3";
import { randomBytes } from "crypto";
const db = new Database("./data/fitai.db");
// GET - Fetch fitness profile for the authenticated user
export async function GET(request: NextRequest) {
try {
const { userId } = await auth();
if (!userId) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const profile = db
.prepare(
`SELECT * FROM fitness_profiles WHERE user_id = ?`
)
.get(userId);
return NextResponse.json({ profile: profile || null });
} catch (error) {
console.error("Error fetching fitness profile:", error);
return NextResponse.json(
{ error: "Failed to fetch fitness profile" },
{ status: 500 }
);
}
}
// POST - Create or update fitness profile for the authenticated user
export async function POST(request: NextRequest) {
try {
const { userId } = await auth();
if (!userId) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const body = await request.json();
const {
height,
weight,
age,
gender,
fitnessGoal,
activityLevel,
medicalConditions,
allergies,
injuries,
} = body;
// Check if profile exists
const existingProfile = db
.prepare(`SELECT id FROM fitness_profiles WHERE user_id = ?`)
.get(userId) as { id: string } | undefined;
const now = Date.now();
if (existingProfile) {
// Update existing profile
db.prepare(
`UPDATE fitness_profiles
SET height = ?,
weight = ?,
age = ?,
gender = ?,
fitness_goal = ?,
activity_level = ?,
medical_conditions = ?,
allergies = ?,
injuries = ?,
updated_at = ?
WHERE user_id = ?`
).run(
height || null,
weight || null,
age || null,
gender || null,
fitnessGoal || null,
activityLevel || null,
medicalConditions || null,
allergies || null,
injuries || null,
now,
userId
);
return NextResponse.json({
message: "Fitness profile updated successfully",
profileId: existingProfile.id,
});
} else {
// Create new profile
const profileId = `fp_${randomBytes(16).toString("hex")}`;
db.prepare(
`INSERT INTO fitness_profiles
(id, user_id, height, weight, age, gender, fitness_goal, activity_level,
medical_conditions, allergies, injuries, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
).run(
profileId,
userId,
height || null,
weight || null,
age || null,
gender || null,
fitnessGoal || null,
activityLevel || null,
medicalConditions || null,
allergies || null,
injuries || null,
now,
now
);
return NextResponse.json(
{
message: "Fitness profile created successfully",
profileId,
},
{ status: 201 }
);
}
} catch (error) {
console.error("Error saving fitness profile:", error);
return NextResponse.json(
{ error: "Failed to save fitness profile" },
{ status: 500 }
);
}
}