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

interface RouteParams {
  params: {
    id: string;
  };
}

function toPublicQuestion(q: ForumQuestion): ForumQuestion {
  const publicFirstName = (q.askerFirstName || q.askerName || '').trim();
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const { askerEmail, askerCompany, source, askerLastName, ...rest } = q;
  return {
    ...rest,
    askerFirstName: publicFirstName || undefined,
    askerName: publicFirstName || undefined,
    askerLastName: undefined,
    askerEmail: undefined,
    askerCompany: undefined,
    source: undefined,
  };
}

export async function GET(
  request: NextRequest,
  { params }: RouteParams
) {
  try {
    const questionId = params.id;

    const question = forumData.getQuestionById(questionId);

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

    // Get answers for this question
    const questionAnswers = forumData.getAnswersByQuestionId(questionId);

    const response: ForumResponse<{ question: ForumQuestion; answers: typeof questionAnswers }> = {
      success: true,
      data: {
        question: {
          ...toPublicQuestion(question),
          answerCount: questionAnswers.length,
        },
        answers: questionAnswers,
      },
    };

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

export async function PATCH(
  request: NextRequest,
  { params }: RouteParams
) {
  try {
    const questionId = params.id;
    const body = await request.json();

    const updatedQuestion = forumData.updateQuestion(questionId, body);

    if (!updatedQuestion) {
      const response: ForumResponse<null> = {
        success: false,
        error: 'Question not found',
      };
      return NextResponse.json(response, { status: 404 });
    }

    const response: ForumResponse<ForumQuestion> = {
      success: true,
      data: updatedQuestion,
    };

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

