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

function deriveNameParts(body: QuestionSubmission): { firstName: string; lastName?: string } {
  const firstName = body.firstName?.trim();
  const lastName = body.lastName?.trim();
  if (firstName) return { firstName, lastName: lastName || undefined };

  const legacyName = body.name?.trim() || '';
  if (!legacyName) return { firstName: '' };
  const parts = legacyName.split(/\s+/).filter(Boolean);
  return { firstName: parts[0] || '', lastName: parts.length > 1 ? parts.slice(1).join(' ') : undefined };
}

function toPublicQuestion(q: ForumQuestion): ForumQuestion {
  const publicFirstName = (q.askerFirstName || q.askerName || '').trim();
  // Strip PII from the public API response
  // 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) {
  try {
    const searchParams = request.nextUrl.searchParams;
    const search = searchParams.get('search')?.toLowerCase() || '';
    const module = searchParams.get('module') || '';
    const status = searchParams.get('status') || '';

    let filteredQuestions = forumData.getQuestions();

    // Apply search filter
    if (search) {
      filteredQuestions = filteredQuestions.filter(
        (q) =>
          q.question.toLowerCase().includes(search) ||
          q.answer?.toLowerCase().includes(search) ||
          q.tags.some((tag) => tag.toLowerCase().includes(search))
      );
    }

    // Apply module filter
    if (module && module !== 'All') {
      filteredQuestions = filteredQuestions.filter((q) => q.module === module);
    }

    // Apply status filter
    if (status) {
      filteredQuestions = filteredQuestions.filter((q) => q.status === status);
    }

    // Sort by creation date (newest first)
    filteredQuestions.sort((a, b) => 
      new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
    );

    // Never expose PII in the public list endpoint.
    const publicQuestions = filteredQuestions.map(toPublicQuestion);

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

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

export async function POST(request: NextRequest) {
  try {
    const body: QuestionSubmission = await request.json();
    const { firstName, lastName } = deriveNameParts(body);

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

    // Create new question
    const newQuestion: ForumQuestion = {
      id: `question-${forumData.getNextQuestionId()}`,
      question: body.question,
      module: body.module,
      tags: [],
      status: 'pending',
      createdAt: new Date().toISOString(),
      askerName: firstName, // only first name
      askerFirstName: firstName,
      askerLastName: lastName,
      askerEmail: body.email,
      askerCompany: body.company,
      source: body.source,
      answerCount: 0,
    };

    forumData.addQuestion(newQuestion);

    const response: ForumResponse<ForumQuestion> = {
      success: true,
      data: toPublicQuestion(newQuestion),
    };

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

