/**
 * Database query functions for careers module
 *
 * This file contains all Prisma queries related to job listings.
 * Separating queries from business logic makes testing easier and
 * provides a clear data access layer.
 */

import { prisma } from "../db";
import type { JobRecord, DatabaseQueryError } from "./types";
import { QUERY_CONFIG, ERROR_MESSAGES, LOG_PREFIX } from "./constants";

/**
 * Fetch all open jobs from the database
 *
 * A job is considered "open" if:
 * - status = 'open'
 * - opening_at <= current time
 * - closing_at is null OR closing_at > current time
 *
 * @returns Object with jobs array and error (if any)
 *
 * @example
 * ```typescript
 * const { jobs, error } = await fetchOpenJobsFromDB();
 * if (error) {
 *   console.error('Failed to load jobs:', error);
 *   return;
 * }
 * console.log(`Found ${jobs.length} open positions`);
 * ```
 */
export async function fetchOpenJobsFromDB(): Promise<{
  jobs: JobRecord[];
  error: DatabaseQueryError | null;
}> {
  const now = new Date();

  try {
    const data = await prisma.jobs.findMany({
      where: {
        status: "open",
        opening_at: { lte: now },
        OR: [{ closing_at: null }, { closing_at: { gt: now } }],
      },
      orderBy: {
        [QUERY_CONFIG.defaultSortField]: QUERY_CONFIG.defaultSortDirection,
      },
      take: QUERY_CONFIG.maxJobsPerQuery,
    });

    return { jobs: data as unknown as JobRecord[], error: null };
  } catch (err) {
    const error = err as Error;
    console.error(LOG_PREFIX.error, ERROR_MESSAGES.fetchFailed, error);
    return {
      jobs: [],
      error: {
        code: "UNEXPECTED_ERROR",
        message: error.message,
      },
    };
  }
}

/**
 * Fetch a single job by slug
 *
 * @param slug - URL-friendly job identifier
 * @returns Job record or null if not found
 *
 * @example
 * ```typescript
 * const job = await fetchJobBySlug('senior-backend-engineer');
 * if (job) {
 *   console.log(job.title_translations.en);
 * }
 * ```
 */
export async function fetchJobBySlug(slug: string): Promise<{
  job: JobRecord | null;
  error: DatabaseQueryError | null;
}> {
  try {
    const data = await prisma.jobs.findFirst({
      where: {
        slug,
        status: "open",
      },
    });

    return { job: data as unknown as JobRecord | null, error: null };
  } catch (err) {
    const error = err as Error;
    console.error(
      LOG_PREFIX.error,
      `Failed to fetch job with slug ${slug}:`,
      error,
    );
    return {
      job: null,
      error: {
        code: "UNEXPECTED_ERROR",
        message: error.message,
      },
    };
  }
}

/**
 * Count total open jobs
 * Useful for displaying "X open positions" without fetching all data
 *
 * @returns Number of open jobs
 */
export async function countOpenJobs(): Promise<number> {
  const now = new Date();

  try {
    const count = await prisma.jobs.count({
      where: {
        status: "open",
        opening_at: { lte: now },
        OR: [{ closing_at: null }, { closing_at: { gt: now } }],
      },
    });

    return count;
  } catch (err) {
    console.error(LOG_PREFIX.error, "Unexpected error counting jobs:", err);
    return 0;
  }
}
