import { NextRequest, NextResponse } from 'next/server';
import { ForumAnswer, AnswerSubmission, ForumResponse } from '@/types/forum';
import * as forumData from '@/lib/forum-data';

export async function POST(request: NextRequest) {
  try {
    const body: AnswerSubmission = await request.json();

    // Validate required fields
    if (!body.questionId || !body.answer || !body.author) {
      const response: ForumResponse<null> = {
        success: false,
        error: 'Missing required fields',
      };
      return NextResponse.json(response, { status: 400 });
    }

    // Verify question exists
    const question = forumData.getQuestionById(body.questionId);
    if (!question) {
      const response: ForumResponse<null> = {
        success: false,
        error: 'Question not found',
      };
      return NextResponse.json(response, { status: 404 });
    }

    // Create new answer
    const newAnswer: ForumAnswer = {
      id: `answer-${forumData.getNextAnswerId()}`,
      questionId: body.questionId,
      answer: body.answer,
      author: body.author,
      authorEmail: body.authorEmail,
      createdAt: new Date().toISOString(),
      isOfficial: false,
    };

    forumData.addAnswer(newAnswer);

    const response: ForumResponse<ForumAnswer> = {
      success: true,
      data: newAnswer,
    };

    return NextResponse.json(response, { status: 201 });
  } catch (error) {
    const response: ForumResponse<null> = {
      success: false,
      error: error instanceof Error ? error.message : 'Failed to create answer',
    };
    return NextResponse.json(response, { status: 500 });
  }
}

// GET endpoint to retrieve answers for a question
export async function GET(request: NextRequest) {
  try {
    const searchParams = request.nextUrl.searchParams;
    const questionId = searchParams.get('questionId');

    if (!questionId) {
      const response: ForumResponse<null> = {
        success: false,
        error: 'questionId is required',
      };
      return NextResponse.json(response, { status: 400 });
    }

    const questionAnswers = forumData.getAnswersByQuestionId(questionId);
    
    // Sort by creation date (oldest first for official answers, then newest for user answers)
    questionAnswers.sort((a, b) => {
      if (a.isOfficial && !b.isOfficial) return -1;
      if (!a.isOfficial && b.isOfficial) return 1;
      return new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime();
    });

    const response: ForumResponse<ForumAnswer[]> = {
      success: true,
      data: questionAnswers,
    };

    return NextResponse.json(response);
  } catch (error) {
    const response: ForumResponse<null> = {
      success: false,
      error: error instanceof Error ? error.message : 'Failed to fetch answers',
    };
    return NextResponse.json(response, { status: 500 });
  }
}

