/**
 * Business logic for careers module
 *
 * This file contains the main service functions that combine
 * queries and transformers to provide clean APIs for the frontend.
 */

import type { JobListing } from "./types";
import { fetchOpenJobsFromDB, fetchJobBySlug, countOpenJobs } from "./queries";
import { transformJobRecords, transformJobRecord } from "./transformers";

/**
 * Fetch all currently open job listings
 *
 * This is the main function used by the careers page to get job listings.
 * It handles all error cases gracefully and always returns an array (never throws).
 *
 * **Error Handling:**
 * - Missing Supabase config → Returns empty array
 * - Missing jobs table → Returns empty array (logs error)
 * - Database error → Returns empty array (logs error)
 * - No jobs found → Returns empty array (no error)
 *
 * @returns Array of job listings (empty if none available or error occurred)
 *
 * @example
 * ```typescript
 * // In a React Server Component
 * export default async function CareersPage() {
 *   const jobs = await fetchOpenJobs();
 *
 *   return (
 *     <div>
 *       {jobs.length > 0 ? (
 *         <JobList jobs={jobs} />
 *       ) : (
 *         <EmptyState />
 *       )}
 *     </div>
 *   );
 * }
 * ```
 */
export async function fetchOpenJobs(): Promise<JobListing[]> {
  const { jobs, error } = await fetchOpenJobsFromDB();

  // Error is already logged in the query layer
  if (error) {
    return [];
  }

  // Transform database records to frontend format
  return transformJobRecords(jobs);
}

/**
 * Fetch a single job by its slug
 *
 * Useful for individual job detail pages (future enhancement)
 *
 * @param slug - URL-friendly job identifier
 * @returns Job listing or null if not found
 *
 * @example
 * ```typescript
 * // For a job detail page at /careers/senior-backend-engineer
 * const job = await fetchJobBySlugService('senior-backend-engineer');
 * if (!job) {
 *   notFound(); // Show 404
 * }
 * ```
 */
export async function fetchJobBySlugService(
  slug: string,
): Promise<JobListing | null> {
  const { job, error } = await fetchJobBySlug(slug);

  if (error || !job) {
    return null;
  }

  return transformJobRecord(job);
}

/**
 * Get count of open jobs
 *
 * Lightweight function to just get the count without fetching all data
 *
 * @returns Number of open positions
 *
 * @example
 * ```typescript
 * const count = await getOpenJobsCount();
 * console.log(`We have ${count} open positions`);
 * ```
 */
export async function getOpenJobsCount(): Promise<number> {
  return await countOpenJobs();
}
