﻿// app/api/performance/workplans/[id]/route.ts
import { NextRequest, NextResponse } from 'next/server';
import prisma from '@/lib/prisma';

export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> | { id: string } }
) {
  try {
    // Await params if it's a Promise (Next.js 15+)
    const { id } = await params;
    const body = await request.json();

    const workPlan = await prisma.workPlan.update({
      where: { id: id },
      data: {
        objective: body.objective,
        target: body.target,
        dueDate: body.dueDate ? new Date(body.dueDate) : undefined,
        progress: body.progress,
        status: body.status,
        tasks: body.tasks,
        updatedAt: new Date(),
      },
    });

    return NextResponse.json(workPlan);
  } catch (error) {
    console.error('Error updating work plan:', error);
    return NextResponse.json(
      { error: 'Failed to update work plan' },
      { status: 500 }
    );
  }
}

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> | { id: string } }
) {
  try {
    const { id } = await params;
    
    const workPlan = await prisma.workPlan.findUnique({
      where: { id: id },
    });

    if (!workPlan) {
      return NextResponse.json(
        { error: 'Work plan not found' },
        { status: 404 }
      );
    }

    return NextResponse.json(workPlan);
  } catch (error) {
    console.error('Error fetching work plan:', error);
    return NextResponse.json(
      { error: 'Failed to fetch work plan' },
      { status: 500 }
    );
  }
}

export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> | { id: string } }
) {
  try {
    const { id } = await params;
    
    await prisma.workPlan.delete({
      where: { id: id },
    });

    return NextResponse.json({ message: 'Work plan deleted successfully' });
  } catch (error) {
    console.error('Error deleting work plan:', error);
    return NextResponse.json(
      { error: 'Failed to delete work plan' },
      { status: 500 }
    );
  }
}