96 lines
2.8 KiB
TypeScript
96 lines
2.8 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server';
|
|
import { auth } from '@clerk/nextjs/server';
|
|
import { getDatabase } from '@/lib/database';
|
|
import { randomBytes } from 'crypto';
|
|
|
|
// GET - List user's fitness goals
|
|
export async function GET(req: NextRequest) {
|
|
try {
|
|
const { userId } = await auth();
|
|
if (!userId) {
|
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
|
}
|
|
|
|
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
|
|
);
|
|
|
|
return NextResponse.json(goals);
|
|
} catch (error) {
|
|
console.error('Error fetching fitness goals:', error);
|
|
return NextResponse.json(
|
|
{ error: 'Internal server error' },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|
|
|
|
// POST - Create new fitness goal
|
|
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 {
|
|
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 }
|
|
);
|
|
}
|
|
|
|
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
|
|
});
|
|
|
|
return NextResponse.json(goal, { status: 201 });
|
|
} catch (error) {
|
|
console.error('Error creating fitness goal:', error);
|
|
return NextResponse.json(
|
|
{ error: 'Internal server error' },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|