/**
 * Support FAQ Validators
 * Input validation for FAQ operations
 */

import type { SupportFAQCategory } from './types';
import { FAQ_CATEGORIES, FAQ_ERRORS } from './constants';
import { CreateFAQInput, UpdateFAQInput, ValidationResult } from './types';

/**
 * Check if a category is valid
 */
export function isValidCategory(category: string): category is SupportFAQCategory {
  return FAQ_CATEGORIES.includes(category as SupportFAQCategory);
}

/**
 * Check if a role has admin permissions for FAQ management
 */
export function hasAdminPermission(role: string): boolean {
  return role === 'ADMIN' || role === 'SUPER_ADMIN';
}

/**
 * Validate required fields for FAQ creation
 */
export function validateCreateInput(input: Partial<CreateFAQInput>): ValidationResult {
  const { category, question, questionAr, answer, answerAr } = input;

  // Check all required fields are present
  if (!category || !question || !questionAr || !answer || !answerAr) {
    return {
      valid: false,
      error: FAQ_ERRORS.MISSING_FIELDS,
    };
  }

  // Validate category
  if (!isValidCategory(category)) {
    return {
      valid: false,
      error: FAQ_ERRORS.INVALID_CATEGORY(FAQ_CATEGORIES),
    };
  }

  return { valid: true };
}

/**
 * Validate update input - only validates category if provided
 */
export function validateUpdateInput(input: UpdateFAQInput): ValidationResult {
  // If category is being updated, validate it
  if (input.category !== undefined && !isValidCategory(input.category)) {
    return {
      valid: false,
      error: FAQ_ERRORS.INVALID_CATEGORY(FAQ_CATEGORIES),
    };
  }

  return { valid: true };
}

/**
 * Sanitize string input by trimming whitespace
 */
export function sanitizeString(value: string | undefined): string | undefined {
  return value?.trim();
}

/**
 * Build update data object from input, sanitizing strings
 */
export function buildUpdateData(
  input: UpdateFAQInput,
  staffId: string
): Record<string, unknown> {
  const data: Record<string, unknown> = {
    updatedBy: staffId,
  };

  if (input.category !== undefined) {
    data.category = input.category;
  }

  if (input.question !== undefined) {
    data.question = sanitizeString(input.question);
  }

  if (input.questionAr !== undefined) {
    data.questionAr = sanitizeString(input.questionAr);
  }

  if (input.answer !== undefined) {
    data.answer = sanitizeString(input.answer);
  }

  if (input.answerAr !== undefined) {
    data.answerAr = sanitizeString(input.answerAr);
  }

  if (input.order !== undefined) {
    data.order = input.order;
  }

  if (input.isPublished !== undefined) {
    data.isPublished = input.isPublished;
  }

  return data;
}
