import { query } from '../db/connection'; import { FaqCategoryRow, FaqEntryRow } from '../models/faq.model'; export type FaqEntryWithCategory = FaqEntryRow & { category_slug: string; category_name: string; }; export type FaqEntryAdminRow = FaqEntryWithCategory & { created_by_name: string | null; updated_by_name: string | null; }; export async function listCategories(activeOnly = false): Promise { if (activeOnly) { return query( `SELECT * FROM faq_categories WHERE is_active = TRUE ORDER BY sort_order ASC, name ASC` ); } return query( `SELECT * FROM faq_categories ORDER BY sort_order ASC, name ASC` ); } export async function getCategoryById(id: number): Promise { const rows = await query(`SELECT * FROM faq_categories WHERE id = $1`, [id]); return rows[0] ?? null; } export async function createCategory(input: { slug: string; name: string; sortOrder?: number; isActive?: boolean; }): Promise { const rows = await query( `INSERT INTO faq_categories (slug, name, sort_order, is_active) VALUES ($1, $2, $3, $4) RETURNING *`, [input.slug, input.name, input.sortOrder ?? 0, input.isActive ?? true] ); return rows[0]; } export async function updateCategory( id: number, patch: Partial<{ slug: string; name: string; sortOrder: number; isActive: boolean }> ): Promise { const c = await getCategoryById(id); if (!c) return null; const rows = await query( `UPDATE faq_categories SET slug = $2, name = $3, sort_order = $4, is_active = $5, updated_at = NOW() WHERE id = $1 RETURNING *`, [ id, patch.slug ?? c.slug, patch.name ?? c.name, patch.sortOrder ?? c.sort_order, patch.isActive ?? c.is_active, ] ); return rows[0] ?? null; } export async function deleteCategory(id: number): Promise { const rows = await query<{ id: number }[]>( `DELETE FROM faq_categories WHERE id = $1 RETURNING id`, [id] ); return rows.length > 0; } export async function listPublicEntries(filters: { categorySlug?: string; search?: string; }): Promise { const conditions = ['e.is_active = TRUE', 'c.is_active = TRUE']; const params: unknown[] = []; let i = 1; if (filters.categorySlug) { conditions.push(`c.slug = $${i++}`); params.push(filters.categorySlug); } if (filters.search?.trim()) { conditions.push(`(e.question ILIKE $${i} OR e.answer_html ILIKE $${i})`); params.push(`%${filters.search.trim()}%`); i++; } return query( `SELECT e.*, c.slug AS category_slug, c.name AS category_name FROM faq_entries e INNER JOIN faq_categories c ON c.id = e.category_id WHERE ${conditions.join(' AND ')} ORDER BY c.sort_order ASC, e.sort_order ASC, e.question ASC`, params ); } export async function listPopularEntries(limit = 5): Promise { return query( `SELECT e.*, c.slug AS category_slug, c.name AS category_name FROM faq_entries e INNER JOIN faq_categories c ON c.id = e.category_id WHERE e.is_active = TRUE AND c.is_active = TRUE ORDER BY (e.helpful_yes - e.helpful_no) DESC, e.view_count DESC LIMIT $1`, [Math.min(limit, 20)] ); } export async function getEntryById(id: string): Promise { const rows = await query( `SELECT e.*, c.slug AS category_slug, c.name AS category_name FROM faq_entries e INNER JOIN faq_categories c ON c.id = e.category_id WHERE e.id = $1`, [id] ); return rows[0] ?? null; } export async function incrementViewCount(id: string): Promise { await query(`UPDATE faq_entries SET view_count = view_count + 1 WHERE id = $1`, [id]); } export async function recordHelpfulVote( faqId: string, voterKey: string, helpful: boolean ): Promise<{ helpfulYes: number; helpfulNo: number; changed: boolean }> { const existing = await query<{ helpful: boolean }[]>( `SELECT helpful FROM faq_helpful_votes WHERE faq_id = $1 AND voter_key = $2`, [faqId, voterKey] ); if (existing[0]) { if (existing[0].helpful === helpful) { const counts = await getHelpfulCounts(faqId); return { ...counts, changed: false }; } await query( `UPDATE faq_helpful_votes SET helpful = $3, created_at = NOW() WHERE faq_id = $1 AND voter_key = $2`, [faqId, voterKey, helpful] ); if (existing[0].helpful) { await query( `UPDATE faq_entries SET helpful_yes = GREATEST(helpful_yes - 1, 0), helpful_no = helpful_no + 1 WHERE id = $1`, [faqId] ); } else { await query( `UPDATE faq_entries SET helpful_no = GREATEST(helpful_no - 1, 0), helpful_yes = helpful_yes + 1 WHERE id = $1`, [faqId] ); } } else { await query( `INSERT INTO faq_helpful_votes (faq_id, voter_key, helpful) VALUES ($1, $2, $3)`, [faqId, voterKey, helpful] ); if (helpful) { await query(`UPDATE faq_entries SET helpful_yes = helpful_yes + 1 WHERE id = $1`, [faqId]); } else { await query(`UPDATE faq_entries SET helpful_no = helpful_no + 1 WHERE id = $1`, [faqId]); } } const counts = await getHelpfulCounts(faqId); return { ...counts, changed: true }; } async function getHelpfulCounts(faqId: string) { const rows = await query<{ helpful_yes: number; helpful_no: number }[]>( `SELECT helpful_yes, helpful_no FROM faq_entries WHERE id = $1`, [faqId] ); return { helpfulYes: rows[0]?.helpful_yes ?? 0, helpfulNo: rows[0]?.helpful_no ?? 0, }; } export async function listAdminEntries(filters: { categoryId?: number; search?: string; isActive?: boolean; }): Promise { const conditions: string[] = ['1=1']; const params: unknown[] = []; let i = 1; if (filters.categoryId != null) { conditions.push(`e.category_id = $${i++}`); params.push(filters.categoryId); } if (filters.isActive != null) { conditions.push(`e.is_active = $${i++}`); params.push(filters.isActive); } if (filters.search?.trim()) { conditions.push(`(e.question ILIKE $${i} OR e.answer_html ILIKE $${i})`); params.push(`%${filters.search.trim()}%`); i++; } return query( `SELECT e.*, c.slug AS category_slug, c.name AS category_name, TRIM(CONCAT(cb.first_name, ' ', cb.last_name)) AS created_by_name, TRIM(CONCAT(ub.first_name, ' ', ub.last_name)) AS updated_by_name FROM faq_entries e INNER JOIN faq_categories c ON c.id = e.category_id LEFT JOIN users cb ON cb.id = e.created_by LEFT JOIN users ub ON ub.id = e.updated_by WHERE ${conditions.join(' AND ')} ORDER BY c.sort_order ASC, e.sort_order ASC, e.created_at DESC`, params ); } export async function createEntry(input: { categoryId: number; question: string; answerHtml: string; isActive?: boolean; sortOrder?: number; userId: string; }): Promise { const rows = await query( `INSERT INTO faq_entries ( category_id, question, answer_html, is_active, sort_order, created_by, updated_by ) VALUES ($1, $2, $3, $4, $5, $6, $6) RETURNING *`, [ input.categoryId, input.question, input.answerHtml, input.isActive ?? true, input.sortOrder ?? 0, input.userId, ] ); return rows[0]; } export async function updateEntry( id: string, patch: Partial<{ categoryId: number; question: string; answerHtml: string; isActive: boolean; sortOrder: number; userId: string; }> ): Promise { const current = await query(`SELECT * FROM faq_entries WHERE id = $1`, [id]); if (!current[0]) return null; const e = current[0]; const rows = await query( `UPDATE faq_entries SET category_id = $2, question = $3, answer_html = $4, is_active = $5, sort_order = $6, updated_by = $7, updated_at = NOW() WHERE id = $1 RETURNING *`, [ id, patch.categoryId ?? e.category_id, patch.question ?? e.question, patch.answerHtml ?? e.answer_html, patch.isActive ?? e.is_active, patch.sortOrder ?? e.sort_order, patch.userId ?? e.updated_by, ] ); return rows[0] ?? null; } export async function deleteEntry(id: string): Promise { const rows = await query<{ id: string }[]>( `DELETE FROM faq_entries WHERE id = $1 RETURNING id`, [id] ); return rows.length > 0; } export async function countEntriesInCategory(categoryId: number): Promise { const rows = await query<{ count: string }[]>( `SELECT COUNT(*)::text AS count FROM faq_entries WHERE category_id = $1`, [categoryId] ); return Number(rows[0]?.count ?? 0); }