/**
 * Data transformation utilities for careers module
 *
 * These functions transform data between database format (snake_case, JSONB)
 * and application format (camelCase, TypeScript interfaces)
 */

import type {
  Lang,
  JobRecord,
  JobListing,
  StringTranslations,
  StringArrayTranslations,
  StringFallback,
} from "./types";
import { SUPPORTED_LANGS } from "./types";
import { DEFAULT_TRANSLATIONS } from "./constants";

/**
 * Parse JSONB string translations from database
 *
 * Safely handles:
 * - Null/undefined values
 * - Missing language keys
 * - Empty strings
 *
 * @param value - JSONB object from database
 * @param fallback - Default value if translation is missing
 * @returns Properly formatted StringTranslations object
 *
 * @example
 * ```typescript
 * const title = parseStringTranslations(
 *   { en: "Engineer", ar: "" },
 *   "Unknown"
 * );
 * // Result: { en: "Engineer", ar: "Unknown" }
 * ```
 */
export function parseStringTranslations(
  value: Record<string, string> | null | undefined,
  fallback: StringFallback = "",
): StringTranslations {
  return SUPPORTED_LANGS.reduce((acc, lang) => {
    const translation = value?.[lang];
    const fallbackValue =
      typeof fallback === "string" ? fallback : (fallback[lang] ?? "");

    // Use translation if it exists and is not empty, otherwise use fallback
    acc[lang] =
      typeof translation === "string" && translation.trim().length > 0
        ? translation
        : fallbackValue;

    return acc;
  }, {} as StringTranslations);
}

/**
 * Parse JSONB string array translations from database
 *
 * Safely handles:
 * - Null/undefined values
 * - Non-array values
 * - Missing language keys
 *
 * @param value - JSONB object from database
 * @returns Properly formatted StringArrayTranslations object
 *
 * @example
 * ```typescript
 * const skills = parseArrayTranslations({
 *   en: ["TypeScript"],
 *   ar: ["TypeScript"]
 * });
 * // Result: { en: ["TypeScript"], ar: ["TypeScript"] }
 * ```
 */
export function parseArrayTranslations(
  value: Record<string, string[]> | null | undefined,
): StringArrayTranslations {
  return SUPPORTED_LANGS.reduce((acc, lang) => {
    const items = value?.[lang];
    acc[lang] = Array.isArray(items) ? items : [];
    return acc;
  }, {} as StringArrayTranslations);
}

/**
 * Transform database job record to frontend job listing
 *
 * This is the main transformation function that converts the database
 * representation (snake_case, JSONB) to the TypeScript interface
 * used throughout the application (camelCase, properly typed)
 *
 * @param record - Job record from Supabase database
 * @returns JobListing interface for frontend use
 *
 * @example
 * ```typescript
 * const dbRecord = await supabase.from('jobs').select('*').single();
 * const jobListing = transformJobRecord(dbRecord.data);
 * // Now jobListing.title.en and jobListing.title.ar are type-safe
 * ```
 */
export function transformJobRecord(record: JobRecord): JobListing {
  return {
    // Identifiers (no transformation needed)
    id: record.id,
    slug: record.slug,

    // Bilingual text fields
    title: parseStringTranslations(record.title_translations),
    departmentLabel: parseStringTranslations(
      record.department_label,
      record.department, // Fallback to raw department name
    ),
    location: parseStringTranslations(
      record.location_translations,
      DEFAULT_TRANSLATIONS.location,
    ),
    contractTypeLabel: parseStringTranslations(
      record.contract_type_label,
      record.contract_type, // Fallback to raw contract type
    ),
    levelLabel: parseStringTranslations(
      record.level_label,
      record.level, // Fallback to raw level
    ),
    salaryRange: parseStringTranslations(
      record.compensation_translations,
      DEFAULT_TRANSLATIONS.salaryRange,
    ),
    applicationInstructions: parseStringTranslations(
      record.application_instructions,
      DEFAULT_TRANSLATIONS.applicationInstructions,
    ),

    // Bilingual array fields
    benefits: parseArrayTranslations(record.benefits),
    skills: parseArrayTranslations(record.skills),
    requirements: parseArrayTranslations(record.requirements),
    responsibilities: parseArrayTranslations(record.responsibilities),
    niceToHave: parseArrayTranslations(record.nice_to_have),
    workdayExpectations: parseArrayTranslations(record.workday_expectations),

    // Metadata (no transformation needed)
    department: record.department,
    contractType: record.contract_type,
    level: record.level,
    status: record.status,

    // Dates (keep as ISO strings for consistency)
    openingAt: record.opening_at,
    closingAt: record.closing_at,
    createdAt: record.created_at,
  };
}

/**
 * Transform multiple job records
 *
 * @param records - Array of job records from database
 * @returns Array of JobListing interfaces
 */
export function transformJobRecords(records: JobRecord[]): JobListing[] {
  return records.map(transformJobRecord);
}
