I am building an application in Next.js, TailwindCSS, Appwrite, and Zustand. Please fix all the bugs and optimize the code

import { NextResponse } from "next/server";
import Together from "together-ai";

const together = new Together({ apiKey: process.env.TOGETHER_API_KEY });

export async function POST(request) {
  try {
    const { action, ...data } = await request.json();

    switch (action) {
      case 'regenerate':
        return handleRegenerate(data);
      case 'chat':
        return handleChat(data);
      default:
        return NextResponse.json({ error: "Invalid action" }, { status: 400 });
    }
  } catch (error) {
    console.error("Error in API:", error);
    return NextResponse.json(
      { error: error.message || "Internal server error" },
      { status: 500 }
    );
  }
}

async function handleRegenerate({ selectedSections, profile, jobDescription, currentResume, message, originalSections }) {
  if (!selectedSections || !profile || !jobDescription || !currentResume || !originalSections) {
    return NextResponse.json(
      { error: "Missing required fields" },
      { status: 400 }
    );
  }

  const prompt = generateRegenerationPrompt(selectedSections, profile, jobDescription, currentResume, message, originalSections);

  const response = await together.chat.completions.create({
    messages: [{ role: "user", content: prompt }],
    model: "meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo",
    max_tokens: 2048,
    temperature: 0.7,
    top_p: 0.7,
    top_k: 50,
    repetition_penalty: 1,
    stop: ["
", "
"],
  });

  const generatedContent = response.choices[0].message.content.trim();

  try {
    const jsonContent = JSON.parse(generatedContent);
    const validatedContent = validateResumeContent(jsonContent);

    // Generate a reply about the regenerated sections
    const replyPrompt = `You have just regenerated the following sections of a resume: ${selectedSections.join(', ')}.
    Here are the original sections:
    ${JSON.stringify(originalSections, null, 2)}

    And here are the regenerated sections:
    ${JSON.stringify(selectedSections.reduce((acc, section) => {
      acc[section] = validatedContent.sections[section];
      return acc;
    }, {}), null, 2)}

    Provide a brief summary of the changes made and any suggestions for further improvements.
    Address the user's request to "improve it more".`;

    const replyResponse = await together.chat.completions.create({
      messages: [{ role: "user", content: replyPrompt }],
      model: "meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo",
      max_tokens: 1024,
      temperature: 0.7,
      top_p: 0.7,
      top_k: 50,
      repetition_penalty: 1,
      stop: ["
", "
"],
    });

    const reply = replyResponse.choices[0].message.content.trim();

    return NextResponse.json({ result: validatedContent, reply });
  } catch (parseError) {
    console.error("Error parsing generated content:", parseError);
    return NextResponse.json(
      { error: "Generated content is not valid JSON" },
      { status: 500 }
    );
  }
}

async function handleChat({ message, chatHistory, resume, jobDescription }) {
  const formattedHistory = chatHistory.map((msg) => ({
    role: msg.type === "user" ? "user" : "assistant",
    content: msg.content,
  }));

  const systemMessage = `
You are a helpful assistant for resume and job application related queries.
You have access to the following information:

Resume:
${JSON.stringify(resume, null, 2)}

Job Description:
${jobDescription}

Please use this information to provide accurate and tailored responses to the user's questions about their resume and job application.
  `;

  const response = await together.chat.completions.create({
    messages: [
      { role: "system", content: systemMessage },
      ...formattedHistory,
      { role: "user", content: message },
    ],
    model: "meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo",
    max_tokens: 1024,
    temperature: 0.7,
    top_p: 0.7,
    top_k: 50,
    repetition_penalty: 1,
    stop: ["
", "
"],
  });

  const reply = response.choices[0].message.content.trim();

  return NextResponse.json({ reply });
}

const sectionPrompts = {
  summary: 'Update the summary to highlight key achievements and skills relevant to the job description.',
  experience: 'Enhance the experience section to emphasize relevant responsibilities and accomplishments.',
  skills: 'Modify the skills section to showcase skills that align closely with the job requirements.',
  education: 'Adjust the education section to highlight relevant courses or honors.',
  // Add more sections and their specific prompts as needed
};

function generateRegenerationPrompt(
    selectedSections,
    profile,
    jobDescription,
    currentResume,
    message,
    originalSections
  ) {
    let sectionInstructions = selectedSections.map(section => {
      const instruction = sectionPrompts[section] || '';
      return `Section: ${section}\nInstruction: ${instruction}\nOriginal Content: ${JSON.stringify(originalSections[section], null, 2)}`;
    }).join('\n\n');

    return `You are a resume writing assistant. Please regenerate the following sections of the resume based on the profile, job description, and current resume. Only modify the selected sections:

  Selected Sections:
  ${selectedSections.join(', ')}

  Profile:
  ${JSON.stringify(profile, null, 2)}

  Job Description:
  ${jobDescription}

  Current Resume:
  ${JSON.stringify(currentResume, null, 2)}

  User Message:
  ${message}

  Instructions:
  For each of the selected sections, follow these specific instructions:
  ${sectionInstructions}

  General Instructions:
  - Only modify the sections specified in the Selected Sections.
  - Maintain the same structure and format as the current resume.
  - Tailor the content to better match the job description and highlight relevant skills and experiences.
  - Ensure that the regenerated sections seamlessly integrate with the rest of the resume.
  - Consider the user's message when making changes: "${message}"
  - Improve the content more than the original, addressing the user's request.
  - Return the entire resume JSON object, including both modified and unmodified sections.

  Return only the JSON object, no additional text.`;
  }

function validateResumeContent(content) {
  const requiredFields = [
    "title",
    "summary",
    "email",
    "phone",
    "location",
    "sections",
  ];
  const requiredSections = [
    "socialLinks",
    "education",
    "experience",
    "skills",
    "certifications",
    "projects",
    "languages",
    "awards",
  ];

  for (const field of requiredFields) {
    if (!content[field]) {
      content[field] = ""; // Set empty string for missing required fields
    }
  }

  for (const section of requiredSections) {
    if (
      !content.sections[section] ||
      !Array.isArray(content.sections[section])
    ) {
      content.sections[section] = [];
    }
  }

  // Ensure each item in each section has an id and valid dates
  for (const section of requiredSections) {
    content.sections[section] = content.sections[section].map((item) => {
      const validatedItem = { ...item, id: item.id || generateUniqueId() };

      // Validate date fields
      [
        "startDate",
        "endDate",
        "issueDate",
        "expirationDate",
        "dateReceived",
      ].forEach((dateField) => {
        if (dateField in validatedItem) {
          validatedItem[dateField] = validateDate(validatedItem[dateField]);
        }
      });

      return validatedItem;
    });
  }

  return content;
}

function validateDate(dateString) {
  if (!dateString || dateString.trim() === "") return "";

  const date = new Date(dateString);
  if (isNaN(date.getTime())) return ""; // Invalid date

  return date.toISOString().split("T")[0]; // Return YYYY-MM-DD format
}

function generateUniqueId() {
  return Math.random().toString(36).substr(2, 9);
}