import { ForumQuestion, ForumAnswer } from '@/types/forum';
import { getInitialForumQuestions, getInitialForumAnswers } from '@/utils/faq-data';

// Shared in-memory data store for forum questions and answers
// In production, this would be replaced with a database

let questions: ForumQuestion[] = getInitialForumQuestions();
let answers: ForumAnswer[] = getInitialForumAnswers();
let nextQuestionId = questions.length + 1;
let nextAnswerId = answers.length + 1;

export function getQuestions(): ForumQuestion[] {
  return [...questions];
}

export function getAnswers(): ForumAnswer[] {
  return [...answers];
}

export function getQuestionById(id: string): ForumQuestion | undefined {
  return questions.find(q => q.id === id);
}

export function getAnswersByQuestionId(questionId: string): ForumAnswer[] {
  return answers.filter(a => a.questionId === questionId);
}

export function addQuestion(question: ForumQuestion): ForumQuestion {
  questions.push(question);
  return question;
}

export function addAnswer(answer: ForumAnswer): ForumAnswer {
  answers.push(answer);
  
  // Update question's answer count and status
  const question = questions.find(q => q.id === answer.questionId);
  if (question) {
    const questionAnswers = getAnswersByQuestionId(question.id);
    question.answerCount = questionAnswers.length;
    if (questionAnswers.length > 0 && question.status === 'pending') {
      question.status = 'answered';
    }
    question.updatedAt = new Date().toISOString();
  }
  
  return answer;
}

export function updateQuestion(id: string, updates: Partial<ForumQuestion>): ForumQuestion | null {
  const index = questions.findIndex(q => q.id === id);
  if (index === -1) return null;
  
  questions[index] = {
    ...questions[index],
    ...updates,
    updatedAt: new Date().toISOString(),
  };
  
  return questions[index];
}

export function getNextQuestionId(): number {
  return nextQuestionId++;
}

export function getNextAnswerId(): number {
  return nextAnswerId++;
}

