﻿import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const employeeId = searchParams.get('employeeId');
    
    let where: any = {};
    if (employeeId) {
      where.employeeId = employeeId;
    }
    
    const workPlans = await prisma.workPlan.findMany({
      where,
      orderBy: { createdAt: 'desc' }
    });
    
    return NextResponse.json(workPlans);
  } catch (error) {
    console.error('Error fetching work plans:', error);
    return NextResponse.json({ error: 'Failed to fetch work plans' }, { status: 500 });
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    
    const workPlan = await prisma.workPlan.create({
      data: {
        employeeId: body.employeeId,
        title: body.objective || body.title,
        objective: body.objective,
        target: body.target,
        dueDate: body.dueDate ? new Date(body.dueDate) : null,
        linkedTargetId: body.linkedTargetId,
        progress: 0,
        status: 'Not Started',
        quarter: new Date().toLocaleDateString(),
        year: new Date().getFullYear(),
        tasks: '[]',
      }
    });
    
    return NextResponse.json(workPlan, { status: 201 });
  } catch (error) {
    console.error('Error creating work plan:', error);
    return NextResponse.json({ error: 'Failed to create work plan' }, { status: 500 });
  }
}
