'use server'

import { prisma } from '@/lib/prisma'
import { getSession } from '@/lib/auth'
import { JOB_INCLUDE, mapJob, buildPriceMap } from '@/lib/jobs-mapper'
import type { RawJob, JobWithRelations, PriceRow } from '@/lib/jobs-mapper'

export type { JobWithRelations } from '@/lib/jobs-mapper'

export async function fetchJobsPageData(): Promise<{ activeJobs: JobWithRelations[]; doneJobs: JobWithRelations[] } | null> {
  const session = await getSession()
  if (!session.userId) return null

  const [active, done, prices] = await Promise.all([
    prisma.claudeJob.findMany({
      where: { user_id: session.userId, status: { notIn: ['DONE'] } },
      include: JOB_INCLUDE,
      orderBy: { created_at: 'desc' },
    }),
    prisma.claudeJob.findMany({
      where: { user_id: session.userId, status: 'DONE' },
      include: JOB_INCLUDE,
      orderBy: { created_at: 'desc' },
      take: 100,
    }),
    prisma.modelPrice.findMany(),
  ])

  const priceMap = buildPriceMap(prices as unknown as PriceRow[])

  return {
    activeJobs: active.map((j) => mapJob(j as unknown as RawJob, priceMap)),
    doneJobs: done.map((j) => mapJob(j as unknown as RawJob, priceMap)),
  }
}
