/**
 * Support FAQ Service
 * Database operations for FAQ management
 */

import { prisma } from '@/lib/db';
import type { SupportFAQCategory } from './types';
import {
  FAQ_DEFAULT_ORDER,
  FAQ_DEFAULTS,
  FAQ_PUBLIC_ORDER,
  FAQ_PUBLIC_SELECT,
} from './constants';
import {
  CreateFAQInput,
  FAQListFilters,
  FAQStats,
  FAQWhereClause,
  PublicFAQ,
  SearchCondition,
} from './types';

/**
 * Build search conditions for a search term
 */
function buildSearchConditions(search: string): SearchCondition {
  return { contains: search, mode: 'insensitive' };
}

/**
 * Build where clause from filters
 */
function buildWhereClause(filters: FAQListFilters): FAQWhereClause {
  const where: FAQWhereClause = {};

  if (filters.category) {
    where.category = filters.category;
  }

  if (filters.isPublished !== undefined) {
    where.isPublished = filters.isPublished;
  }

  if (filters.search) {
    const searchCondition = buildSearchConditions(filters.search);
    where.OR = [
      { question: searchCondition },
      { questionAr: searchCondition },
      { answer: searchCondition },
      { answerAr: searchCondition },
    ];
  }

  return where;
}

/**
 * Get all FAQs with optional filters (staff view - includes all fields)
 */
export async function listFAQs(filters: FAQListFilters = {}) {
  const where = buildWhereClause(filters);

  const faqs = await prisma.support_faqs.findMany({
    where,
    orderBy: FAQ_DEFAULT_ORDER,
  });

  return faqs;
}

/**
 * Get FAQ statistics
 */
export async function getFAQStats(faqs: { isPublished: boolean }[]): Promise<FAQStats> {
  const categoryCounts = await prisma.support_faqs.groupBy({
    by: ['category'],
    _count: { id: true },
  });

  return {
    total: faqs.length,
    published: faqs.filter((f) => f.isPublished).length,
    draft: faqs.filter((f) => !f.isPublished).length,
    byCategory: Object.fromEntries(
      categoryCounts.map((c) => [c.category, c._count.id])
    ),
  };
}

/** Options for public FAQ query */
export interface PublicFAQOptions {
  category?: SupportFAQCategory;
  search?: string;
}

/**
 * Get published FAQs for public view
 */
export async function getPublishedFAQs(options: PublicFAQOptions = {}): Promise<PublicFAQ[]> {
  const where: FAQWhereClause = { isPublished: true };

  if (options.category) {
    where.category = options.category;
  }

  if (options.search) {
    const searchCondition = buildSearchConditions(options.search);
    where.OR = [
      { question: searchCondition },
      { questionAr: searchCondition },
      { answer: searchCondition },
      { answerAr: searchCondition },
    ];
  }

  const faqs = await prisma.support_faqs.findMany({
    where,
    select: FAQ_PUBLIC_SELECT,
    orderBy: FAQ_PUBLIC_ORDER,
  });

  // Add categorySlug for frontend routing
  return faqs.map((faq) => ({
    ...faq,
    categorySlug: faq.category.toLowerCase().replace(/_/g, '-'),
  }));
}

/**
 * Get a single FAQ by ID
 */
export async function getFAQById(id: string) {
  return prisma.support_faqs.findUnique({
    where: { id },
  });
}

/**
 * Create a new FAQ
 */
export async function createFAQ(input: CreateFAQInput, staffId: string) {
  // Get next order number if not provided
  let order = input.order ?? FAQ_DEFAULTS.ORDER;
  if (order === 0) {
    const maxOrder = await prisma.support_faqs.findFirst({
      where: { category: input.category },
      orderBy: { order: 'desc' },
      select: { order: true },
    });
    order = (maxOrder?.order ?? 0) + 1;
  }

  return prisma.support_faqs.create({
    data: {
      category: input.category,
      question: input.question.trim(),
      questionAr: input.questionAr.trim(),
      answer: input.answer.trim(),
      answerAr: input.answerAr.trim(),
      order,
      isPublished: input.isPublished ?? FAQ_DEFAULTS.IS_PUBLISHED,
      createdBy: staffId,
    },
  });
}

/**
 * Update an existing FAQ
 */
export async function updateFAQ(id: string, data: Record<string, unknown>) {
  return prisma.support_faqs.update({
    where: { id },
    data,
  });
}

/**
 * Delete an FAQ
 */
export async function deleteFAQ(id: string) {
  return prisma.support_faqs.delete({
    where: { id },
  });
}

/**
 * Check if an FAQ exists
 */
export async function faqExists(id: string): Promise<boolean> {
  const faq = await prisma.support_faqs.findUnique({
    where: { id },
    select: { id: true },
  });
  return faq !== null;
}
